One of the most useful features of C# is the ability to work with collections, which are groups of related objects that can be manipulated as a single entity. This article, will explore the concept of a set collection in C# so read this guide thoroughly if you are interested in understating set collection in C#.
What is Set Collection in C#
A set collection is a type of collection in C# that represents a group of unique elements. In other words, each element in a set collection is distinct, and there are no duplicates. The set collection is defined by the HashSet class in C#.
The HashSet class implements the Set<T> interface, which provides a set of methods for working with sets, further here is an example that demonstrate how to create set collection in C# along with perform some necessary functions:
using System.Collections.Generic;
class Program
{
static void Main()
{
// create a new set collection
HashSet mySet = new HashSet();
// add some elements to the set
mySet.Add("BMW");
mySet.Add("Mercedes");
mySet.Add("AUDI");
// print out the elements in the set
Console.WriteLine("Set contains:");
foreach (string item in mySet)
{
Console.WriteLine(item);
}
bool isInSet = mySet.Contains("AUDI");
Console.WriteLine("Is AUDI in the set? " + isInSet);
// remove an element from the set
mySet.Remove("BMW");
// print out the updated set
Console.WriteLine("Set contains:");
foreach (string item in mySet)
{
Console.WriteLine(item);
}
// clear the set
mySet.Clear();
}
}
In this example, we create a new set collection using the HashSet<string> class. We then add some elements to the set using the Add() method and print out the contents of the set using a foreach loop.
Next, the code uses the Contain() method to check if an element is in the set and uses the remove() function to remove an element from the set. We print out the updated set again and finally clear the set using the Clear() method.
Conclusion
A set collection in C# is a group of unique elements that can be manipulated as a single entity. The HashSet class in C# provides a set of methods for working with set collections, including fast lookup operations. Set collections are an ideal choice when you need to work with a group of unique elements and perform fast lookup operations on them.