How do I convert Foreach statement into linq expression?

前端 未结 2 524
粉色の甜心
粉色の甜心 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条回答
  • 2021-01-11 16:28
    var list = ids.Select(id => new Book(id)).ToList();
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
提交回复
热议问题