Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert Foreach statement into linq expression?

Tags:

c#

linq

how to convert below foreach into linq expression?

var list = new List<Book>();

foreach (var id in ids)
{
    list.Add(new Book{Id=id});
}
like image 950
seagull Avatar asked Jun 12 '14 21:06

seagull


People also ask

Which is better foreach or LINQ?

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?

What does => mean in LINQ?

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.


2 Answers

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.

like image 140
p.s.w.g Avatar answered Nov 15 '22 16:11

p.s.w.g


var list = ids.Select(id => new Book(id)).ToList();
like image 25
SLaks Avatar answered Nov 15 '22 17:11

SLaks