2017-04-17 45 views
1

我在我的应用程序上使用SparkPost向我和客户发送电子邮件。为了做到这一点,我需要使用C#序列化一个数组。我有下面的代码似乎没有工作,我不知道为什么。LINQ在自定义类型的列表中选择?

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 ="[email protected]" 
    }, 
    new Recipient() { 
     address ="[email protected]" 
    }, 
    new Recipient() { 
     address ="[email protected]" 
    }, 
    new Recipient() { 
     address ="[email protected]" 
    } 
} 

任何帮助将是巨大的,谢谢!

特定错误:

Error CS1503 Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable' to 'app.Recipient'

Error CS1950 The best overloaded Add method 'List.Add(Recipient)' for the collection initializer has some invalid arguments

请求字符串:

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 = "[email protected]" 
     }, 
     subject = subject, 
     html = emailBody 
    }, 
    recipients = new List<Recipient>() { 
     toAddresses.Select(addr => new Recipient() { 
      address => addr 
     }) 
    } 
} 

));

+0

请问您可以用什么方式描述您当前的代码“似乎没有工作?”你是否收到错误信息?与您预期的不同的输出? – StriplingWarrior

+0

@StriplingWarrior查看更新后的问题。 –

回答

3

好像你需要简单的映射

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 = "[email protected]" 
     }, 
     subject = subject, 
     html = emailBody 
    }, 
    recipients = toAddresses.Select(addr => new Recipient() { address = addr}).ToList() 
} 
+4

为什么当他现有的代码不起作用时会工作? – StriplingWarrior

+0

@StriplingWarrior:因为当调用'List '构造函数时,编译器期望LINQ查询产生一个* single *接收者。它给出了一个错误:'参数'#1'不能将'System.Collections.Generic.IEnumerable '表达式转换为'Recipient''类型。 –

+2

@WillemVanOnsem我认为问题的关键在于理由应该成为答案的一部分。 – juharr