Sets
Sets and dictionaries are fast at finding, retrieving, and removing items. They're unordered and rely on object hash codes.
Retrieving an item in array and list could be fast because we know the index and can access it directly. However, how to know the index? Yes, we have to sort it first. How if we work on dynamic big amount of data, it has to be sorted regularly when a new item added to the list. Moreover, inserting and deleting item to the list or array require the item to be shifted. Another problem is how about the duplicate items in list or array?
In short, HashSet not only faster and more efficient while working on big amount of data, but also has another additional methods comparing to array or list.
Inserting data in HashSet
Inserting data in hashSet looks same as inserting data in array.
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
Accessing data in HashSet
Accesing the data in HashSet is pretty simple, just call the index of the HashSet
evenNumbers.ElementAt(2); //result: 2
Removing data in HashSet
Updating the data acts as adding the data in array. Updating means replacing the current data in array.
HashSet<int> numbers = new HashSet<int>();
for (int i = 0; i < 20; i++) {
numbers.Add(i);
}
numbers.RemoveWhere(IsOdd);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
if (numbers.Contains(0)) {
numbers.Remove(0);
}
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
private static bool IsOdd(int i)
{
return ((i % 2) == 1);
}
private static void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
Console.Write(" {0}", i);
Console.WriteLine(" }");
}
// result: numbers contains 10 elements: { 0 2 4 6 8 10 12 14 16 18 }
// result: numbers contains 9 elements: { 2 4 6 8 10 12 14 16 18
More HashSet Operations
Unite items in one HashSet with another HashSet.
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);
// result: 0 2 4 6 8 1 3 5 7 9
HashSet could prevent a duplicate item by assigning hash code to each item. Code below show how to get the hash code of the items.
foreach (string number in numbers)
Console.WriteLine(number.GetHashCode());