I have a list in C#:
var list = new List();
list.AddRange(GetGreenCars());
list.AddRange(GetBigCars());
list.AddRange(
Given you override the .Equals()
method for Car
to determine one car object is the same as another car object, then the following should work w/o writing an extension method.
var list = new List<Car>();
list.AddRange(GetGreenCars()?.Except(list) ?? new List<Car>());
list.AddRange(GetBigCars()?.Except(list) ?? new List<Car>());
list.AddRange(GetSmallCars()?.Except(list) ?? new List<Car>());
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).
Assuming your Get*Cars() return Lists of Car, another option could be:
var list = new List<Car>();
GetGreenCars().ForEach(c => { if (!list.Contains(c)) list.Add(c); });
GetBigCars().ForEach(c => { if (!list.Contains(c)) list.Add(c); });
GetSmallCars().ForEach(c => { if (!list.Contains(c)) list.Add(c); });