Is there an AddUnique method similar to Addrange() for alist in C#
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();
Another option is to do something like:
public static void AddUnique<T>( this IList<T> self, IEnumerable<T> items )
{
foreach(var item in items)
if(!self.Contains(item))
self.Add(item);
}
var list = new List<Car>();
list.AddUnique(GetGreenCars());
list.AddUnique(GetBigCars());
list.AddUnique(GetSmallCars());
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).