2017-04-17 42 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