I have two collections
List<Car> currentCars = GetCurrentCars();
List<Car> newCars = GetNewCars();
You can use
var currentCarsNotInNewCars = currentCars.Except(newCars); var newCarsNotInCurrentCars = newCars.Except(currentCars);
But this has no performance benefit over the
foreach solution. It just looks cleaner.
Also, be aware of the fact, that you need to implement
IEquatable<T> for your
Car class, so the comparison is done on the ID and not on the reference.
Performancewise, a better approach would be to not use a
List<T> but a
Dictionary<TKey, TValue> with the ID as the key:
var currentCarsDictionary = currentCars.ToDictionary(x => x.ID); var newCarsDictionary = newCars.ToDictionary(x => x.ID); var currentCarsNotInNewCars = currentCarsDictionary.Where(x => !newCarsDictionary.ContainsKey(x.Key)) .Select(x => x.Value); var newCarsNotInCurrentCars = newCarsDictionary.Where(x => !currentCarsDictionary.ContainsKey(x.Key)) .Select(x => x.Value);