Create a list with LINQ

Viewed 84

I have an class called message, inside which I have a IEnumerable called copies.

I need to create a new Recipient class object with the copies content.

In order to do that, I created a Recipient list, then interacting on copies using ForEach method; But I took so much code lines, and it doesn't feel good for me. There is a way to do that using LINQ methods?

I'll put below what I've done so far.

CODE USING FOREACH (PROPERLY WORKING)

var recipientListWithForEach = new List<Recipient>();

foreach (var item in message.Copies)
{
    recipientListWithForEach.Add(new Recipient
    {
        EmailAddress = new EmailAddress
        {
            Address = item
        }
    });
}

CODE USING LINQ (NOT WORKING, IDK WHY)

var recipientListWithLINQ = new List<Recipient> {
    message.Copies.Select(item => new Recipient {
        EmailAddress = new EmailAddress {
            Address = item
        }
    });
};

Giving the error message:

not possible convert from "System.Collections.Generic.IEnumerable<Microsoft.Graph.Recipient>" to "Microsoft.Graph.Recipient"

3 Answers

Actually problem that you have not used proper constructor for List

// working
new List<T>(items)

Following is list initialisation syntax, which accepts not an IEnumerable but single items separated by coma.

// bad
new List<T> {items}
// working
new List<T> {item1, item2}

So, just correct your code

var recipientListWithLINQ = new List<Recipient> (
    message.Copies.Select(item => new Recipient {
        EmailAddress = new EmailAddress {
            Address = item
        }
    ));
};

But LINQ query should be simplier

var recipientListWithLINQ = 
    message.Copies.Select(item => new Recipient {
        EmailAddress = new EmailAddress {
            Address = item
        }
    )
    .ToList();

Update per comment: since you need single item, you don't really need IEnumerable. Just pick first item from Copies and construct your Recipient. And probably pick a better name for a variable?

var item = message.Copies.First();
var recipientListWithLINQ = new Recipient {
    EmailAddress = new EmailAddress {
        Address = item
    }
};

Original answer:

You need to convert your IEnumerable to List with ToList()

var recipientListWithLINQ = message.Copies.Select(item => new Recipient {
    EmailAddress = new EmailAddress {
        Address = item
    }
}).ToList();

You're doing a little bit too much work! .Select returns the list you need. Wrapping that list in a Recipient constructor is not needed.

var recipientListWithLINQ =
    message.Copies.Select(item => new Recipient {
        EmailAddress = new EmailAddress {
            Address = item
        }
    });
Related