Joe Scotto
Joe Scotto

Reputation: 10877

LINQ Select within List of custom type?

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
        })
    }
}

));

Upvotes: 3

Views: 2557

Answers (1)

Fabio
Fabio

Reputation: 32455

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()
}

Upvotes: 7

Related Questions