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

前端 未结 9 1510
[愿得一人]
[愿得一人] 2021-01-07 16:32

I have a list in C#:

       var list = new List();
       list.AddRange(GetGreenCars());
       list.AddRange(GetBigCars());
       list.AddRange(         


        
相关标签:
9条回答
  • 2021-01-07 17:05

    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>());
    
    0 讨论(0)
  • 2021-01-07 17:06

    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).

    0 讨论(0)
  • 2021-01-07 17:11

    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); });
    
    0 讨论(0)
提交回复
热议问题