有没有办法从列表中排除数据,具体取决于列表中是否包含另一个数组中的ID?
例如,给定:
int[] excludedCities = new int[] { 342, 344, 22, 19, 2 };
List<Cities> cities = new List<Cities>();
我想在excludedCities数组中删除id为的城市。有没有比迭代列表更简单的方法?
答案 0 :(得分:1)
HashSet<int> excludedCityHash = new HashSet<int>(excludedCities);
IEnumerable<City> filtered = cities.Where(city => !excludedCityHash.Contains(city.ID));
你可以这样做:
IEnumerable<City> filtered = cities.Where(city => !excludedCities.Contains(city.ID));
......但对于少数被排除在外的城市,表现将开始受到影响。
答案 1 :(得分:1)
如果您乐意从城市列表中删除元素,那么您可以这样做:
cities.RemoveAll(c => excludedCities.Contains(c.Id));
否则,你可以这样做:
List<Cities> result = cities.Where(c => !excludedCities.Contains(c.Id))
.ToList();