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

荒凉一梦 提交于 2019-12-13 11:37:56

问题


I have a List that has duplicates of objects. To solve that, I need to convert the List into a HashSet (in C#). Does anyone know how?


回答1:


Make sure your object's class overrides Equals and GetHashCode and then you can pass the List<T> to HashSet<T> constructor.

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

You may see: What is the best algorithm for an overridden System.Object.GetHashCode?




回答2:


An alternative way would be

var yourlist = new List<SomeClass>();

// [...]

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

Note that this is only possible, if SomeClass overrides GetHashCode and Equals in some way. This is also true for

var uniqueObjs = new HashSet<SomeType>(yourOriginalList);

Otherwise you could implement you own IEqualityComnparer-class and pass it to distinct.

Note that with the Distinct() approach, you can also look for distinct property values of the object in the list:

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

and some more...




回答3:


If your type implements IEquatable<T>, Equals() and GetHashCode() correctly, then you don't need to do the de-duplication yourself. You can use Linq's Distinct() to do so like this:

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


来源:https://stackoverflow.com/questions/31052953/how-to-convert-listt-to-hashsett-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!