seagull
seagull

Reputation: 237

How do I convert Foreach statement into linq expression?

how to convert below foreach into linq expression?

var list = new List<Book>();

foreach (var id in ids)
{
    list.Add(new Book{Id=id});
}

Upvotes: 12

Views: 22620

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149078

It's pretty straight forward:

var list = ids.Select(id => new Book { Id = id }).ToList();

Or if you prefer query syntax:

var list = (from id in ids select new Book { Id = id }).ToList();

Also note that the ToList() is only necessary if you really need List<Book>. Otherwise, it's generally better to take advantage of Linq's lazy evaluation abilities, and allow the Book objects objects to only be created on demand.

Upvotes: 23

SLaks
SLaks

Reputation: 888203

var list = ids.Select(id => new Book(id)).ToList();

Upvotes: 1

Related Questions