In this article [Show more]
Adding Elements to a HashSet in C#
In C#, the HashSet<T> class provides a high-performance way to store unique items. It ensures that no duplicates exist in the collection and provides efficient operations for adding, removing, and checking for membership. This article explains how to add elements to a HashSet using the Add method, covering practical use cases and examples.
Adding Elements with Add
Method Signature
public bool Add(T item)
- Returns: true if the element was successfully added (was not already present), otherwise false.
- Parameters:
- item: The element to add to the HashSet.
Example Code
using System;
using System.Collections.Generic;
public class HashSetAddExample
{
public static void Main()
{
// Create a HashSet of integers
HashSet<int> numbers = new HashSet<int>();
// Add elements using the Add method
bool isAdded1 = numbers.Add(1);
bool isAdded2 = numbers.Add(2);
bool isAdded3 = numbers.Add(1); // Duplicate
// Display results of the Add method
Console.WriteLine("Was 1 added the first time? " + isAdded1); // True
Console.WriteLine("Was 2 added? " + isAdded2); // True
Console.WriteLine("Was 1 added the second time? " + isAdded3); // False
// Print all unique elements
Console.WriteLine("Current elements in HashSet:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
Adding Custom Objects
To add custom objects to a HashSet, ensure that the object's GetHashCode and Equals methods are properly overridden.
using System;
using System.Collections.Generic;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override bool Equals(object obj)
{
if (obj is Person other)
{
return Name == other.Name && Age == other.Age;
}
return false;
}
public override int GetHashCode()
{
return HashCode.Combine(Name, Age);
}
}
public class HashSetAddCustomObjectsExample
{
public static void Main()
{
// Create a HashSet of Person objects
HashSet<Person> people = new HashSet<Person>();
// Add custom objects
people.Add(new Person { Name = "Alice", Age = 30 });
people.Add(new Person { Name = "Bob", Age = 25 });
people.Add(new Person { Name = "Alice", Age = 30 }); // Duplicate
// Display all unique people
Console.WriteLine("Unique people in HashSet:");
foreach (Person person in people)
{
Console.WriteLine($"{person.Name}, Age: {person.Age}");
}
}
}
Practical Use Cases
- Data Deduplication: Efficiently filter out duplicate data entries when importing or processing records.
- Set Operations: Use the Add method to build sets and perform operations like union, intersection, and difference.
Conclusion
The Add method of HashSet<T> is a powerful tool for adding unique elements to your collections efficiently. By understanding its return value and properly implementing equality methods for custom objects, you can ensure that your data remains unique and manageable.