TanvirArjel TanvirArjel - 1 year ago 110
C# Question

Foreach Loop In LINQ in C#

I would like to replace the foreach loop in the following code with LINQ ForEach() Expression:

List<int> idList = new List<int>() { 1, 2, 3 };

IEnumerable<string> nameList = new List<string>();

foreach (int id in idList)
var Name = db.Books.Where(x => x.BookId == id).Select(x => x.BookName);

Any Help Please!!

Rob Rob
Answer Source

Your code doesn't quite work (you're adding an IEnumerable<string> to a List<string>). You also won't need ForEach, since you're constructing the list:

You can do this:

var nameList = idList.SelectMany(id => db.Books.Where(x => x.BookId == id)
                     .Select(x => x.BookName)).ToList();

But then you're hitting the database for each ID. You can grab all the books at once with :

var nameList = db.Books.Where(b => idList.Contains(b.BookId))
                       .Select(b => b.BookName).ToList();

Which will only hit the database once.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download