Tag Archives: Unique

C# : How do you keep a list with UNIQUE values only?

Probelm

Given code :

var items = new List<string>();
items.Add("string1");
items.Add("string2");
items.Add("string3");
items.Add("string1");

foreach(var item in items){
    Console.WriteLine(item);
}

The output will show

string1
string2
string3
string1

Answer

Use a HashSet Example:

var items = new HashSet<string>();
items.Add("string1");
items.Add("string2");
items.Add("string3");
items.Add("string1");

foreach(var item in items){
    Console.WriteLine(item);
}

The output will show

string1
string2
string3

Gotchas

When overwriting object’s Equal method in your class you have added to the HashSet. HashSet calls the Equals method in which is calling your overridden Equals method. If you are comparing a string, strings are compared with Ordinal Case Sensitive string comparison by default. Make sure you are comparing your object’s fields properly and safely for situations such as this.