LINQ在自定义类型列表中选择?

时间:2017-04-17 14:47:39

标签: c# linq

我在我的应用程序中使用SparkPost向我和客户发送电子邮件。为此,我需要使用C#序列化一个数组。我有以下代码,似乎没有工作,我不知道为什么。

recipients = new List<Recipient>() {
    toAddresses.Select(addr => new Recipient() {
        address = addr.ToString()
    })
}

toAddresses只是一个包含电子邮件地址的List<string>

收件人类:

class Recipient {
    public string address;
}

该LINQ选择的输出应如下所示:

recipients = new List<Recipient>(){
    new Recipient() {
        address ="joe_scotto@1.net"
    },
    new Recipient() {
        address ="joe_scotto@2.net"
    },
    new Recipient() {
        address ="joe_scotto@1.net"
    },
    new Recipient() {
        address ="jscotto@2.com"
    }
}

任何帮助都会很棒,谢谢!

特定错误:

  

错误CS1503参数1:无法转换为&#39; System.Collections.Generic.IEnumerable&#39;到&#39; app.Recipient&#39;

     

错误CS1950最佳重载添加方法&#39; List.Add(收件人)&#39;对于集合初始化程序有一些无效的参数

请求字符串:

wc.UploadString("https://api.sparkpost.com/api/v1/transmissions", JsonConvert.SerializeObject(
new {
    options = new {
        ip_pool = "sa_shared"
    },
    content = new {
        from = new {
            name = "a Sports",
            email = "no-reply@colorizer.a.com"
        },
        subject = subject,
        html = emailBody
    },
    recipients = new List<Recipient>() {
        toAddresses.Select(addr => new Recipient() {
            address => addr
        })
    }
}

));

1 个答案:

答案 0 :(得分:5)

好像你需要简单的映射

var recipients = toAddresses.Select(addr => new Recipient { address = addr }).ToList();

您不能将IEnumerable用作列表初始化的参数

var recipients = new List<Recipient>() { toAddresses.Select...  }

初始化逻辑会在您List.Add中传递的每个项目上调用{ },因此它希望Recepient的实例用逗号分隔,但是当您通过IEnumerable时,它会失败

List<T>有重载构造函数,接受IEnumerable<T>作为参数,因此您可以使用此

var recepients = new List<Recepient>(toAddresses.Select(addr => new Recipient {address = addr}));

但就我个人而言,简单的映射似乎更具可读性。

var message = new 
{
    options = new 
    { 
        ip_pool = "sa_shared"
    },
    content = new 
    {
        from = new 
        {
            name = "a Sports",
            email = "no-reply@colorizer.a.com"
        },
        subject = subject,
        html = emailBody
    },
    recipients = toAddresses.Select(addr => new Recipient() { address = addr}).ToList()
}