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

前端 未结 9 1684
[愿得一人]
[愿得一人] 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:06

    A List doesn't seem to be the appropriate collection here. You probably want an ISet implementation such as HashSet (or SortedSet if you need ordering).

    To allow this, you will need to write an IEqualityComparer 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 too).

提交回复
热议问题