Use a HashSet<string>
instead of a List<string>
. It is prepared to perform a better performance because you don't need to provide checks for any items. The collection will manage it for you. That is the difference between a list
and a set
. For sample:
HashSet<string> set = new HashSet<string>();
set.Add("a");
set.Add("a");
set.Add("b");
set.Add("c");
set.Add("b");
set.Add("c");
set.Add("a");
set.Add("d");
set.Add("e");
set.Add("e");
var total = set.Count;
Total is 5
and the values are a
, b
, c
, d
, e
.
The implemention of List<T>
does not give you nativelly. You can do it, but you have to provide this control. For sample, this extension method
:
public static class CollectionExtensions
{
public static void AddItem<T>(this List<T> list, T item)
{
if (!list.Contains(item))
{
list.Add(item);
}
}
}
and use it:
var list = new List<string>();
list.AddItem(1);
list.AddItem(2);
list.AddItem(3);
list.AddItem(2);
list.AddItem(4);
list.AddItem(5);