Reputation: 1279
I have a string array
named batches
that contains batchnames. I want to compare it with Batch entity
and get all the records that matches with batchName field of entity. I am using Entity Framework 6
.
class Batch
{
int batchId { get; set;}
string batchname { get; set;}
string info { get; set;}
DateTime date { get; set;}
}
Right now I am doing it like this using foreach
foreach(var item in batches)
{
var res=opt.Batch.Where(i=>i.batchname==item).FirstOrDefault();
batchlist.Add(res);
}
How can I do it with LINQ
without using foreach
Upvotes: 0
Views: 1125
Reputation: 9377
What about something like:
var batchlist = opt.Batch.Where(x => batches.Contains(x.batchname)).ToList();
Upvotes: 2
Reputation: 1469
This will get you a list of Batch objects:
var resultList = opt.Batch.Join(batches, left => left.batchname, right => right, (left, right) => left
changing the last 'left' to 'right', will give you a string list of batch names
var resultList = opt.Batch.Join(batches, left => left.batchname, right => right, (left, right) => right
Upvotes: 0
Reputation: 816
You can replace the whole foreach loop and keep the 2 lines of code, replacing i.batchname==item
with the following:
batches.Contains(i.batchname)
You can then add all items at once to your list as this will return all batches where the name is in the batches array.
The variable res will return an enumerable which can then either be looped around to add to your list or you can use a list that allows AddRange()
Hope this helps.
Upvotes: 4
Reputation: 7438
Something like below will help.
foreach(var item in batches)
{
batchlist.AddRange(opt.Batch.Where(i=>i.batchname.Any(item => i.batchname==item)).ToList());
}
Upvotes: 0