【发布时间】:2016-04-04 18:34:33
【问题描述】:
我有Fruit的列表:
List<Fruit>
其中Fruit 具有以下属性/字段:
id
name
color
给定一个整数数组:
int[] ids = new [] {1,2,8};
如何过滤我的列表,以便排除 id 在数组中的水果?
【问题讨论】:
-
到目前为止你尝试过什么?如果您可以显示一些代码(即使它不起作用),您会在这里得到更多响应。
我有Fruit的列表:
List<Fruit>
其中Fruit 具有以下属性/字段:
id
name
color
给定一个整数数组:
int[] ids = new [] {1,2,8};
如何过滤我的列表,以便排除 id 在数组中的水果?
【问题讨论】:
var l = new List<Fruit>();
var exceptions = new int[] {1,2,8};
var filtered = l.Where(x=> !exceptions.Contains(x.id));
请注意,这将返回一个新过滤的IEnumerable<Fruit>;它不会从原始列表中删除项目。要真正从列表中删除它们,您可以改用:
l.RemoveAll(x => exceptions.Contains(x.id));
【讨论】: