[英]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.