我有一个具有重复对象的List.要解决这个问题,我需要将List转换为HashSet(在C#中).有谁知道怎么样?
Hab*_*bib 56
确保你的对象的类重写Equals和GetHashCode,然后你可以通过List<T>向HashSet<T> 构造器.
var hashSet = new HashSet<YourType>(yourList);
Run Code Online (Sandbox Code Playgroud)
您可能会看到:重写的System.Object.GetHashCode的最佳算法是什么?
另一种方法是
var yourlist = new List<SomeClass>();
// [...]
var uniqueObjs = yourlist.Distinct(); //Gives you a List with unique Objects of the List.
Run Code Online (Sandbox Code Playgroud)
请注意,这是唯一可能的,如果SomeClass覆盖GetHashCode并Equals以某种方式.这也是如此
var uniqueObjs = new HashSet<SomeType>(yourOriginalList);
Run Code Online (Sandbox Code Playgroud)
否则,您可以实现自己的IEqualityComnparer-class并将其传递给distinct.
请注意,通过该Distinct()方法,您还可以在列表中查找对象的不同属性值:
var uniqueNames = yourlist.Select(obj => obj.Name).Distinct();
Run Code Online (Sandbox Code Playgroud)
还有一些......
如果您的类型实现IEquatable<T>,Equals()并且GetHashCode()正确,那么您不需要自己进行重复数据删除。您可以使用 LinqDistinct()来这样做:
myList = myList.Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38516 次 |
| 最近记录: |