TanvirArjel TanvirArjel - 16 days ago 8
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);
nameList.Add(Name);
}


Any Help Please!!

Rob Rob
Answer

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.