Search This Blog

Thursday, November 21, 2013

HashSet C# Example

C# > Generics > HashSet

HashSet is an optimized set of value collection. A set is a collection that contains no duplicate elements.

Note: The elements are not in a particular order

Example:
 
Use UnionWith to merge two sets with millions of elements
            
            HashSet<int> s1 = new HashSet<int>();
            HashSet<int> s2 = new HashSet<int>();
            for (int i = 0; i < 1000000; i++)
            {
                s1.Add(i);
            }
            for (int i = 1000001; i < 2000000; i++)
            {
                s2.Add(i);
            }
            HashSet<int> s3 = new HashSet<int>(s1);
            s3.UnionWith(s2);
            if (s3.Contains(1500000))
            {
                MessageBox.Show("1,500,000 element found in HashSet"); 
            }