I'm using SparkPost on my application to send emails to me and clients. In order to do this, I need to serialize an array using C#. I have the following code that does not seem to be working and I have no idea why.
recipients = new List<Recipient>() {
toAddresses.Select(addr => new Recipient() {
address = addr.ToString()
})
}
toAddresses is just a List<string> with email addresses.
Recipient class:
class Recipient {
public string address;
}
The output of that LINQ select should look like this:
recipients = new List<Recipient>(){
new Recipient() {
address ="[email protected]"
},
new Recipient() {
address ="[email protected]"
},
new Recipient() {
address ="[email protected]"
},
new Recipient() {
address ="[email protected]"
}
}
Any help would be great, thanks!
Specific Errors:
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
Request String:
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
})
}
}
));
Seems like you need simple mapping
var recipients = toAddresses.Select(addr => new Recipient { address = addr }).ToList();
You cannot use IEnumerable as parameter for list initialization
var recipients = new List<Recipient>() { toAddresses.Select... }
Initialization logic will call List.Add on every item you pass in { }, so it expects instances of Recepient separated by comma, but when you pass there IEnumerable it fail.
List<T> have overload constructor which accept IEnumerable<T> as argument so you can use this
var recepients = new List<Recepient>(toAddresses.Select(addr => new Recipient {address = addr}));
But on my own opinion simple mapping seems more readable.
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With