Search code examples
c#collectionsunique

Is there an AddUnique method similar to Addrange() for alist in C#


I have a list in C#:

       var list = new List<Car>();
       list.AddRange(GetGreenCars());
       list.AddRange(GetBigCars());
       list.AddRange(GetSmallCars());

the issue is that some of the same cars get returned in different functions and I don't want them in the list more than once. Each car has a unique Name attribute. Is there anyway I can have something like this above but will only add items if they are unique ?


Solution

  • A List<T> doesn't seem to be the appropriate collection here. You probably want an ISet<T> implementation such as HashSet<T> (or SortedSet<T> if you need ordering).

    To allow this, you will need to write an IEqualityComparer<T> implementation that defines equality between cars according to the Name property. If this is the 'canonical' definition of car-equality, you can also consider directly building this definition into the Car type itself (object.Equals, object.GetHashCode and ideally implement IEquatable<T> too).