Reputation: 32059
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!!
Upvotes: 0
Views: 2891
Reputation: 38333
nameList.AddRange(
db.Books.Where(x => idList.Contains(x.BookId))
.Select(x => x.BookName)
.ToList());
This will generate an IN statement in the SQL, thereby only doing a single select.
One thing to be aware of is the performance of IN degrades as the set (idList in this case) gets bigger. In the case of a large set, you can batch the set and do multiple queries:
int start = 0;
int batch = 1000;
while (start < idList.Count())
{
var batchSet = idList.Skip(start).Take(batch);
nameList.AddRange(
db.Books.Where(x => batchSet.Contains(x.BookId))
.Select(x => x.BookName)
.ToList());
start += batch;
}
Upvotes: 0
Reputation: 1076
To answer your specific question, you can do this:
List<int> idList = new List<int>() { 1, 2, 3 };
List<string> nameList = new List<string>();
idList.ForEach(id => {
var Name = db.Books.Where(x => x.BookId == id).Select(x => x.BookName);
nameList.Add(Name);
});
Upvotes: -1
Reputation: 27357
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.
Upvotes: 5
Reputation: 5510
Why not a select?
List<int> idList = new List<int>() { 1, 2, 3 };
List<string> nameList = idList
.Select(id => db.Books.Where(x => x.BookId == id).Select(x => x.BookName))
.ToList();
Or better yet: refactorise and select...
int[] idList = new int[] { 1, 2, 3 };
List<string> nameList = db.Books
.Where(x => idList.Contains(x.BookId))
.Select(x => x.BookName))
.ToList();
Upvotes: 1