Reputation: 53
Is there any way to exclude data from a list depending on whether the list contains one of the ID in another array?
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. Is there an easier way than iterating the list?
Upvotes: 1
Views: 675
Reputation: 56433
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();
Upvotes: 1
Reputation: 1973
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.
Upvotes: 1