Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uniq in C#

Tags:

c#

list

unique

Is there an easy way to get only the unique values out of a list of strings in C#? My google-fu is failing me today.

(I know I can put them in another structure and pull them out again. I'm looking for stupidly-easy, like Ruby's .uniq method. C# has bloody well everything else, so I'm probably just using the wrong synonym.)

Specifically, this is coming from Linq, so if Linq had a built-in way to select only unique strings, that would be even cooler.

like image 792
Ken Avatar asked Dec 05 '22 07:12

Ken


2 Answers

List<string> strings = new string[] { "Hello", "Hello", "World" }.ToList();

strings = strings.Distinct().ToList();
like image 87
Quintin Robinson Avatar answered Dec 07 '22 19:12

Quintin Robinson


In .net 3.5:-

var strings = new List<string> { "one", "two", "two", "three" };
var distinctStrings = strings.Distinct(); // IEnumerable<string>
var listDistinctStrings = distinctStrings.ToList(); // List<string>

Boom shaka-laka!

like image 27
ljs Avatar answered Dec 07 '22 19:12

ljs