C# Data Structures Guide: List vs HashSet vs
SortedSet (and Multiset Equivalent)
This document explains the most important collection data structures in C#: List, HashSet, and
SortedSet. It also explains how to retrieve data from them and how to implement something similar
to a multiset in C# (which does not exist as a built■in structure).
1. List
List<T> is essentially a dynamic array.
Key properties:
• Allows duplicate elements.
• Maintains insertion order.
• Supports indexing (access by position).
List<int> list = new List<int>();
[Link](10);
[Link](20);
[Link](10); // duplicates allowed
[Link](list[0]);
Retrieving data from List:
• Using index: list[0]
• Using foreach loop
2. HashSet
HashSet<T> is a set structure based on a hash table.
Key properties:
• Does NOT allow duplicate elements.
• Element order is not guaranteed.
• Very fast lookup (usually O(1)).
HashSet<int> set = new HashSet<int>();
[Link](10);
[Link](20);
[Link](10); // duplicate ignored
Retrieving data from HashSet:
• Use foreach loop
• Convert to List using ToList()
• Use ElementAt() from LINQ
3. SortedSet
SortedSet<T> is similar to HashSet but keeps elements sorted.
Key properties:
• No duplicate elements.
• Elements are automatically sorted.
• Implemented using a balanced binary tree.
SortedSet<int> set = new SortedSet<int>();
[Link](30);
[Link](10);
[Link](20);
// Result: 10 20 30 (always sorted)
Retrieving data:
• foreach loop
• [Link] → smallest element
• [Link] → largest element
4. Multiset Equivalent in C#
C# does not provide a built■in multiset like C++. A multiset allows duplicate elements but still
keeps them grouped and counted.
Common ways to implement a multiset in C#:
• Dictionary<T,int> (count occurrences)
• SortedDictionary<T,int> if you need ordering
Dictionary<int,int> multiset = new Dictionary<int,int>();
void Add(int x)
{
if([Link](x))
multiset[x]++;
else
multiset[x] = 1;
}
Comparison Table
Feature List HashSet SortedSet
Duplicates allowed Yes No No
Maintains order Yes (insertion) No Yes (sorted)
Index access Yes No No
Search complexity O(n) O(1) O(log n)
Internal structure Dynamic Array Hash Table Balanced Tree