C# Language An overview of c# collections HashSet

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

This is a collection of unique items, with O(1) lookup.

HashSet<int> validStoryPointValues = new HashSet<int>() { 1, 2, 3, 5, 8, 13, 21 };
bool containsEight = validStoryPointValues.Contains(8); // O(1)

By way of comparison, doing a Contains on a List yields poorer performance:

List<int> validStoryPointValues = new List<int>() { 1, 2, 3, 5, 8, 13, 21 };
bool containsEight = validStoryPointValues.Contains(8); // O(n)

HashSet.Contains uses a hash table, so that lookups are extremely fast, regardless of the number of items in the collection.



Got any C# Language Question?