Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

how to convert below foreach into linq expression?

var list = new List<Book>();

foreach (var id in ids)
{
    list.Add(new Book{Id=id});
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
423 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...