0

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

0

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

What about something like:

var batchlist = opt.Batch.Where(x => batches.Contains(x.batchname)).ToList();

Comments

0

Something like below will help.

foreach(var item in batches)
{
  batchlist.AddRange(opt.Batch.Where(i=>i.batchname.Any(item => i.batchname==item)).ToList());
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.