How to use HashSet in c#

Time:2021-7-30

Translation link:https://www.infoworld.com/art…

HashSet is an optimized unordered set, which provides high-speed search and high-performance search of elementsSet setOperation, and HashSet was introduced in. Net 3.5System.Collection.GenericNamespace, this article will discuss how to use this HashSet.

To run the case code for this article, you need to install itVisual Studio 2019, if not, you can download it from the official website.

Create a. Net core console program using vs

First, I create a. Net core console program through vs2019. For the creation, please refer to the following steps:

  • Open the visual studio ide
  • Click createCreate new project
  • stayCreate new projectWindow, select from the list of templates:Console App (.NET Core)
  • Click next
  • stayConfigure your new projectFill in your project name and storage path in the interface

In this way, we have created a new project. Later in this article, we will share some necessary knowledge of HashSet.

What exactly is HashSet

The so-called HashSet refers toSystem.Collections.GenericUnder namespaceHashSet<T>Class, which is a high-performance and unordered collection. Therefore, HashSet cannot perform sorting operations, nor can it contain any duplicate elements, and HashSet cannot use indexes like arrays. Therefore, you can’t use for loops on HashSet, but can only use foreach for iteration. HashSet is usually used to deal with the uniqueness of elements, which has ultra-high performance.

HashSet<T>The following interfaces are implemented:


public class HashSet<T> : System.Collections.Generic.ICollection<T>,
System.Collections.Generic.IEnumerable<T>, 
System.Collections.Generic.IReadOnlyCollection<T>,
System.Collections.Generic.ISet<T>,
System.Runtime.Serialization.IDeserializationCallback,
System.Runtime.Serialization.ISerializable
{
}

HashSet can only contain unique elements, and its internal structure has been specially optimized for this. It is worth noting that HashSet can also store a single null value. We can draw a conclusion: if you want to have a set with unique value, HashSet is your best choice, and it also has ultra-high retrieval performance.

Find an element from the HashSet

If you want to judge whether an element is in the HashSet, it is recommended to use contains. The code is as follows:


        static void Main(string[] args)
        {
            HashSet<string> hashSet = new HashSet<string>();
            hashSet.Add("A");
            hashSet.Add("B");
            hashSet.Add("C");
            hashSet.Add("D");
            if (hashSet.Contains("D"))
                Console.WriteLine("The required element is available.");
            else
                Console.WriteLine("The required element isn’t available.");
            Console.ReadKey();
        }

Element uniqueness in HashSet

If you insert a duplicate element into a HashSet, its internals will ignore this operation and not throw an exception like other collections. Next, show the code:


        static void Main(string[] args)
        {
            HashSet<string> hashSet = new HashSet<string>();
            hashSet.Add("A");
            hashSet.Add("B");
            hashSet.Add("C");
            hashSet.Add("D");
            hashSet.Add("D");
            Console.WriteLine("The number of elements is: {0}", hashSet.Count);
            Console.ReadKey();
        }

When you execute this program, the output results are as follows:

How to use HashSet in c#

Now consider the following code snippet, which shows how duplicate elements are eliminated.


        static void Main(string[] args)
        {
            string[] cities = new string[] {
                "Delhi",
                "Kolkata",
                "New York",
                "London",
                "Tokyo",
                "Washington",
                "Tokyo"
            };
            HashSet<string> hashSet = new HashSet<string>(cities);
            foreach (var city in hashSet)
            {
                Console.WriteLine(city);
            }
        }

When you finish the above procedure, the duplicate city names have been removed.

How to use HashSet in c#

Remove element from HashSet

To delete an element from a HashSet, you can call the remove method. Its syntax structure is as follows:


public bool Remove (T item);

If the element is found in the collection, the remove method deletes the element and returns true, otherwise it returns false.

The following code snippet shows how to use the remove method to delete elements in a HashSet


string item = "D";
if(hashSet.Contains(item))
{
   hashSet.Remove(item);
}

If you want to delete all the elements in the HashSet, you can call the clear method.

Set operation of HashSet

HashSet provides many methods forSet setOperationally, for example:Intersectwith, Unionwith, ispropersubsetof, exceptwith, and symmetricexceptwith

IsProperSubsetOf

Ispropersubsetof is used to judge whether a HashSet is a complete subset of a set. See the following example:


HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D" };
HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X" };
HashSet<string> setC = new HashSet<string>() { "A", "B", "C", "D", "E" };
if (setA.IsProperSubsetOf(setC))
   Console.WriteLine("setC contains all elements of setA.");
if (!setA.IsProperSubsetOf(setB))
   Console.WriteLine("setB does not contains all elements of setA.");

If you execute the above program, you will see the following output on the console:

How to use HashSet in c#

UnionWith

The Unionwith method is often used to merge collections, such as the following code:


HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "B", "C", "X", "Y" };
setA.UnionWith(setB);
foreach(string str in setA)
{
   Console.WriteLine(str);
}

When you finish executing the above code, setb set will be swallowed by seta set. Finally, seta set will include:"A", "B", "C", "D", "E", "X", and "Y"

IntersectWith

The intersectwith method is often used to represent the intersection of two hashsets. The following example may give you a better understanding:


HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y"};
setA.IntersectWith(setB);
foreach (string str in setA)
{
    Console.WriteLine(str);
}

When you run the above program, only the elements existing in both hashsets will be output to the console. The output results are as follows:

How to use HashSet in c#

ExceptWith

The exceptwith method represents mathematical subtraction. The time complexity is O (n). Suppose you have two HashSet sets called seta and setb, and use the following statement.


setA.ExceptWith(setB);

The returned elements are: the final result in seta but not in setb. If you don’t understand it, use the following code to help you understand it:


HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y" };
setA.ExceptWith(setB);
foreach (string str in setA)
{
   Console.WriteLine(str);
}

When you execute the above program, elements B, D and e will be output to the console.

How to use HashSet in c#

SymmetricExceptWith

The symmetricexceptwith method is often used to modify a HashSet to store elements that are unique to both hashsets. In other words, I want elements that are incomplete in both sets. If I don’t understand, consider the following code segment:


HashSet<string> setA = new HashSet<string>() { "A", "B", "C", "D", "E" };
HashSet<string> setB = new HashSet<string>() { "A", "X", "C", "Y" };
setA.SymmetricExceptWith(setB);
foreach (string str in setA)
{
  Console.WriteLine(str);
}

When you finish executing the above code, you will find that the elements in seta but not in setb and the elements in setb but not in seta will be output to the console.

How to use HashSet in c#

We know that the average complexity of the array is O (n), where n represents the number of elements in the array, and the complexity of accessing an element in the HashSet is O (1). This constant complexity determines that HashSet is a very good choice for fast retrieval and execution of set set operations. You can also use list to store some elements in a specified order, You can also include duplicate values.

More high quality dry goods: see my GitHub:dotnetfly