Filter List By items in Array (LINQ)

时间:2016-04-04 18:34:34

标签: c# 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?

1 个答案:

答案 0 :(得分:2)

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));