how to convert below foreach into linq expression?
var list = new List();
foreach (var id in ids)
{
list.Add(new Book{Id=id});
}
var list = ids.Select(id => new Book(id)).ToList();
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.