Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting unique items from a list [duplicate]

Tags:

c#

list

unique

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.

like image 840
domgreen Avatar asked Sep 07 '09 09:09

domgreen


People also ask

How do I get unique values from a column with repeated values?

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.

How do I get distinct items from a list?

List<int> myList = list. Distinct(). ToList();


2 Answers

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(); 
like image 130
LukeH Avatar answered Sep 24 '22 22:09

LukeH


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 
like image 21
Vinay Sajip Avatar answered Sep 21 '22 22:09

Vinay Sajip