What is the fastest / most efficient way of getting all the distinct items from a list?
I have a List<string>
that possibly has multiple repeating items in it and only want the unique values within the list.
In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.
List<int> myList = list. Distinct(). ToList();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With