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 ?
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With