How do I convert Foreach statement into linq expression?

前端 未结 2 545
粉色の甜心
粉色の甜心 2021-01-11 15:44

how to convert below foreach into linq expression?

var list = new List();

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


        
2条回答
  •  萌比男神i
    2021-01-11 16:32

    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. 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.

提交回复
热议问题