简体   繁体   English

如何从基于另一个数组的列表中排除数据?

[英]How can I exclude data from list based on another array?

Is there any way to exclude data from a list depending on whether the list contains one of the ID in another array? 有什么方法可以根据列表中是否包含另一个数组中的ID来从列表中排除数据?

For example, given: 例如,给定:

int[] excludedCities = new int[] { 342, 344, 22, 19, 2 };
List<Cities> cities = new List<Cities>(); 

I want to remove the cities with the id in excludedCities array. 我想删除ID为excludeCities数组的城市。 Is there an easier way than iterating the list? 有比遍历列表更简单的方法吗?

HashSet<int> excludedCityHash = new HashSet<int>(excludedCities);
IEnumerable<City> filtered = cities.Where(city => !excludedCityHash.Contains(city.ID));

You can do just: 您可以执行以下操作:

IEnumerable<City> filtered = cities.Where(city => !excludedCities.Contains(city.ID));

... but for more than a small handful of excluded cities, performance will start to suffer. ...但是对于少数几个被排除的城市,效果将开始下降。

If you're happy removing the elements from the cities list then you can do: 如果您很乐意从城市列表中删除元素,则可以执行以下操作:

cities.RemoveAll(c => excludedCities.Contains(c.Id));

otherwise, you can do: 否则,您可以执行以下操作:

List<Cities> result = cities.Where(c => !excludedCities.Contains(c.Id))
                            .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用另一个列表中的数据更新列表的内容? - How can I update the contents of a list with data from another list? 如何从带有where子句的列表中获取数据到另一个列表? - How can I get data from a list with a where clause to another list? 如何将数组中存在的数据拆分为另一个数组。? - How can I split data present in an array into another array.? 如何根据gridview中单击的项目将对象列表中的数据传递到DialogFragment Textview - How Can I pass data from a list of objects to DialogFragment Textviews based on the clicked item in gridview Linq根据另一个列表的成员资格从一个列表中排除自定义对象(C#) - Linq to exclude a custom object from one List based on membership of another List (c#) 如何从另一个不同类型的列表中排除项目? - How to exclude items from another list of different type? 如何从数据网格中排除锯齿状数组的第一行? - How do I exclude the first row of a jagged array from a data grid? 我们如何将数据从一个列表传输到另一个列表 - How can we transfer data from one list to another 如何根据某些条件从另一个列表中创建新的字符串列表? - How do I make a new list of strings from another list based on certain criteria? 我如何从另一个类访问一个类数组 - How can I access a class array from another class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM