是否有类似的AddRange()在C#中的ALIST方法AddUnique [英] Is there an AddUnique method similar to Addrange() for alist in C#
问题描述
我在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 ?
推荐答案
A 列表< T>
似乎并不在这里适当的集合。你可能需要一个的ISet< T>
实施如 的HashSet< T>
(或 的SortedSet< T>
如果需要排序)
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).
要实现这一点,你需要编写。一个的IEqualityComparer< T>
执行定义根据名称
性能车之间的平等。如果这是汽车平等的规范的定义,也可以考虑直接建设这个定义成车
类型本身(的Object.Equals
, object.GetHashCode
和理想的实施 IEquatable< T>
太)
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).
这篇关于是否有类似的AddRange()在C#中的ALIST方法AddUnique的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!