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

leora picture leora · Dec 28, 2011 · Viewed 37.9k times · Source

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 ?

Answer

Ivo picture Ivo · Dec 28, 2011

One choice is to add them and remove the repeated ones:

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