Hey all,
What is the fasters / most efficient way of getting all the unique items out of a C# list?
I have List that possiably has multiple repeating items in it and only want the unique values within the list.
Thanks
Hey all,
What is the fasters / most efficient way of getting all the unique items out of a C# list?
I have List that possiably has multiple repeating items in it and only want the unique values within the list.
Thanks
You can use the Distinct method to return an IEnumerable<T> of distinct items:
var uniqueItems = yourList.Distinct();
And if you need the sequence of unique items returned as a List<T>, you can add a call to ToList:
var uniqueItemsList = yourList.Distinct().ToList();
Use a HashSet<T>. For example:
var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
Console.WriteLine(s);
prints
A B D C
Apart from the Distinct extension method of LINQ, you could use a HashSet<T> object that you initialise with your collection. This is most likely more efficient than the LINQ way, since it uses hash codes (GetHashCode) rather than an IEqualityComparer).
In fact, if it's appropiate for your situation, I would just use a HashSet for storing the items in the first place.