how to convert below foreach into linq expression?
var list = new List<Book>();
foreach (var id in ids)
{
list.Add(new Book{Id=id});
}
Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code. So your experience is that LINQ is faster and makes code harder to read and to maintain?
The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.
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.
var list = ids.Select(id => new Book(id)).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With