Reputation: 9850
I need to write a LINQ
where clause where it should satisfy the condition of multiple records.
For example, in the Animal
table. I have 3 columns
Id, Name, age
I need to find all Animals
where the Name is an array
. ['Ant', 'Mouse', 'Turtle']
var aniList= db.Animals.Where(c =>
c.Name== arrAni[0] ||
c.Name== arrAni[1] ||
c.Name== arrAni[2] );
However, the above is hardcoded. I need to directly insert the List into the where clause so it gets filtered out. How can I do this ?
Upvotes: 2
Views: 90
Reputation: 30512
string[] animalNames = new string[] {"ant", "mouse", "turtle"}
var desiredAnimals = animalList
.Where(animal => animalNames.Contains(animal.Name));
In words: from the collection of Animals
in animalList
, keep only those Animals
whose Name
is in the collection of AnimalNames
Upvotes: 0
Reputation: 13676
Well, you could simply use Linq .Contains
method:
var aniList = db.Animals.Where(c => arrAni.Contains(c.Name));
Upvotes: 4