However a HashSet collection is not sorted and cannot contain duplicate elements. At that time when you need to collection in sorted order then you can use the List<t> class together with the Sort method or if you are on .net framework 4 then you can use the SortedSet<t> class. But in this article i will show you that we can use the array class to sort the hashset object, see the following example:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //Create hashset object of the int type HashSet<int> objHash = new HashSet<int>(); // add items to hashset object objHash.Add(14); objHash.Add(12); objHash.Add(11); objHash.Add(13); // Print all elements of the hashset object Console.WriteLine("before sort"); foreach (int i in objHash) { Console.WriteLine(i); } //Declare a new Array object of int type int[] arrInt; // bind items to array from hashset object arrInt = objHash.ToArray(); // Sort the array Array.Sort(arrInt); // Clear hashset object objHash.Clear(); //Merge the array into hashset object with sort order objHash.UnionWith(arrInt); //Print the all items of the hashset object Console.WriteLine("After sort"); foreach (int i in objHash) { Console.WriteLine(i); } } } }
The above program will produce the following output:
before sort
14
12
11
13
after sort
11
12
13
14