Reputation: 237
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
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