C# HashSet
In C#, a HashSet is a collection that contains unique elements. It provides high-performance set operations like union, intersection, and symmetric difference. In this tutorial, we'll discuss how to use HashSet in C#.
Syntax
The syntax for creating a HashSet in C# is as follows:
HashSet<int> set = new HashSet<int>();
This creates a HashSet of type int. You can replace "int" with any other data type.
Example
Let's say we want to create a HashSet of strings containing the names of students in a class. Here's how we can implement it:
HashSet<string> students = new HashSet<string>();
students.Add("John");
students.Add("Sarah");
students.Add("Bob");
students.Add("John"); // This will be ignored since "John" is already in the set
Now, we can use the HashSet to get the count of students and check if a specific student is in the set:
Console.WriteLine(students.Count); // Output: 3
Console.WriteLine(students.Contains("Sarah")); // Output: True
Output
When we run the example code above, the output will be:
3
True
This is because we added four students to the set, but "John" was not added again since it already existed in the set. We then printed the count of students and checked if "Sarah" was in the set (which was True).
Explanation
In the example above, we created a HashSet called "students" and added four students to it. Since "John" was already added, it was not added again. We then used the HashSet to get the count of students and check if "Sarah" was in the set.
Use
HashSets are useful when you need to store a collection of unique elements and perform set operations like union, intersection, and symmetric difference quickly and efficiently.
Important Points
- HashSet provides high-performance set operations like union, intersection, and symmetric difference.
- The elements in a HashSet are unordered and unique.
- You can iterate over a HashSet using a foreach loop.
- You can remove elements from a HashSet using the Remove or RemoveWhere method.
Summary
In this tutorial, we discussed how to use HashSet in C#. We covered the syntax, example, output, explanation, use, and important points of HashSet in C#. With this knowledge, you can now use HashSet in your C# code to store unique elements and perform set operations like union, intersection, and symmetric difference.