Joper Joper - 2 months ago 6x
C# Question

C# more efficient way of comparing two collections

I have two collections

List<Car> currentCars = GetCurrentCars();
List<Car> newCars = GetNewCars();

I don't want to use foreach loop or something because i think there should be much better way of doing this.

I am looking for more efficient way to compare this collections and to get results:

  1. List of cars which are in newCars and not in currentCars

  2. List of cars which are not in newCars and in currentCars

Type Car has int property Id.

There was an answer, which is already deleted saying
What i mean by saying efficient: less code, less mechanics, and more readable cases

So thinking this way what is the cases i have?

What would be less code, less mechanics, and more readable cases?


You can use Except:

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);