如何在 C# 中将 List<T> 转换为 HashSet<T>?

How to convert List<T> to HashSet<T> in C#?

我有一个包含重复对象的列表。为了解决这个问题,我需要将 List 转换为 HashSet(在 C# 中)。有人知道怎么做吗?

确保对象的 class 覆盖 EqualsGetHashCode,然后您可以将 List<T> 传递给 HashSet<T> constructor

var hashSet = new HashSet<YourType>(yourList);

您可能会看到:What is the best algorithm for an overridden System.Object.GetHashCode?

另一种方法是

var yourlist = new List<SomeClass>();

// [...]

var uniqueObjs = yourlist.Distinct();  //Gives you a List with unique Objects of the List.

请注意,这只有在 SomeClass 以某种方式覆盖 GetHashCodeEquals 时才有可能。

也是如此
var uniqueObjs = new HashSet<SomeType>(yourOriginalList);

否则你可以实现你自己的 IEqualityComnparer-class 并将其传递给不同的。

请注意,使用 Distinct() 方法,您还可以在列表中查找对象的不同 属性 值:

var uniqueNames = yourlist.Select(obj => obj.Name).Distinct(); 

还有更多...

如果您的类型正确实现了 IEquatable<T>Equals()GetHashCode(),那么您不需要自己进行重复数据删除。您可以使用 Linq 的 Distinct() 这样做:

myList = myList.Distinct().ToList();