prog_prog
prog_prog

Reputation: 391

Filter List By items in Array (LINQ)

I have list of Fruit:

List<Fruit>

where Fruit has the following properties/fields:

id
name
color

Given an array of integers:

int[] ids = new [] {1,2,8};

How can I filter my list so that it will exclude the fruits whose id is in the array?

Upvotes: 2

Views: 9433

Answers (1)

Zev Spitz
Zev Spitz

Reputation: 15307

var l = new List<Fruit>();
var exceptions = new int[] {1,2,8};
var filtered = l.Where(x=> !exceptions.Contains(x.id));

Note that this will return a new filtered IEnumerable<Fruit>; it will not remove the items from the original list. To actually remove them from the list, you can use instead:

l.RemoveAll(x => exceptions.Contains(x.id));

Upvotes: 4

Related Questions