Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 284
leora Avatar asked Dec 28 '11 05:12

leora


People also ask

What is AddRange?

The AddRange method is called, with the list as its argument. The result is that the current elements of the list are added to the end of the list, duplicating all the elements.

What is AddRange in Linq?

In this post I'm going to explain you about Linq AddRange method. This method is quite useful when you want to add multiple elements to a end of list. Following is a method signature for this. public void AddRange( IEnumerable<T> collection ) To Understand let's take simple example like following.


1 Answers

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(); 
like image 115
Ivo Avatar answered Sep 20 '22 14:09

Ivo