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

Joe*_*tto 2 c# linq

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

recipients = new List<Recipient>() {
    toAddresses.Select(addr => new Recipient() {
        address = addr.ToString()
    })
}
Run Code Online (Sandbox Code Playgroud)

toAddresses只是一个List<string>电子邮件地址.

收件人类:

class Recipient {
    public string address;
}
Run Code Online (Sandbox Code Playgroud)

LINQ select的输出应如下所示:

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"
    }
}
Run Code Online (Sandbox Code Playgroud)

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

特定错误:

错误CS1503参数1:无法从'System.Collections.Generic.IEnumerable'转换为'app.Recipient'

错误CS1950集合初始化程序的最佳重载Add方法'List.Add(Recipient)'有一些无效的参数

请求字符串:

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
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

));

Fab*_*bio 5

好像你需要简单的映射

var recipients = toAddresses.Select(addr => new Recipient { address = addr }).ToList();
Run Code Online (Sandbox Code Playgroud)

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

var recipients = new List<Recipient>() { toAddresses.Select...  }
Run Code Online (Sandbox Code Playgroud)

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

List<T>有重载构造函数接受IEnumerable<T>作为参数,所以你可以使用它

var recepients = new List<Recepient>(toAddresses.Select(addr => new Recipient {address = addr}));
Run Code Online (Sandbox Code Playgroud)

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

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()
}
Run Code Online (Sandbox Code Playgroud)

  • 当他现有的代码不起作用时,为什么会这样? (4认同)
  • @WillemVanOnsem我认为关键是原因应该是答案的一部分. (2认同)
  • 好编辑.您可能还想提一下,他可以将`Select`结果传递给`new List <Recipient()`的*构造函数*. (2认同)
  • @AndriiLitvinov:我之所以这么说,是因为我认为OP可能认为他在做什么.事实上他是一个新的List并试图通过初始化器传递值让我觉得他之前看到过类似的方法(使用构造函数参数)并且只是在两种语法之间混淆了.法比奥在这个答案上做得很好. (2认同)