2017-04-17 16 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>は、あなたがこの

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

を使用できるように引数としてIEnumerable<T>を受け入れるしかし、私自身の意見に単純なマッピングをより読み思わ過負荷コンストラクタを持っています。

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クエリが*単一の*受信者になることを期待しています。 'Argument'#1 'は 'System.Collections.Generic.IEnumerable 'の式を' Recipient 'とタイプ変換できません。 –

+2

@WillemVanOnsem私は、理由は答えの一部でなければならないと主張したと思います。 – juharr

関連する問題