Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a Hashset .Net 3.5

Tags:

How can one sort a HashSet<string> in c# .Net 3.5 ?

like image 878
ViV Avatar asked May 08 '12 09:05

ViV


People also ask

Can we sort HashSet in C#?

The HashSet class implements the ICollection, IEnumerable, IReadOnlyCollection, ISet, IEnumerable, IDeserializationCallback, and ISerializable interfaces. In HashSet, the order of the element is not defined. You cannot sort the elements of HashSet.

Is sorting possible in HashSet?

Hence sorting of HashSet is not possible. However, the elements of the HashSet can be sorted indirectly by converting into List or TreeSet, but this will keep the elements in the target type instead of HashSet type.

Is C# HashSet thread safe?

Collections and related namespaces can be read by multiple threads safely. This means HashSet can be safely read by multiple threads.

What is the use of HashSet in C#?

A HashSet is usually used for high-performance operations involving a set of unique data. Since HashSet contains only unique elements, its internal structure is optimized for faster searches. Note that you can store a single null value in a HashSet.


1 Answers

You don't. By definition, a HashSet is not sorted.

If you want a sorted hash set, then you should use a SortedSet. The methods it exposes are essentially a superset of those provided by HashSet, including the ability to sort its contents.

like image 149
Cody Gray Avatar answered Oct 12 '22 14:10

Cody Gray