Sharon Watinsan
Sharon Watinsan

Reputation: 9850

Linq filter using a List

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

Answers (2)

Harald Coppoolse
Harald Coppoolse

Reputation: 30512

Use Enumerable.Contains

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

Fabjan
Fabjan

Reputation: 13676

Well, you could simply use Linq .Contains method:

var aniList = db.Animals.Where(c => arrAni.Contains(c.Name));

Upvotes: 4

Related Questions