tags:

views:

276

answers:

2
+3  Q: 

uniq in C#

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.

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

strings = strings.Distinct().ToList();
Quintin Robinson
but dude... no boom shaka-laka?!
kronoz
You see I just like BOOOM! But I wasn't sure if I should.. =P
Quintin Robinson
+6  A: 

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!

kronoz
You and your verbose examples, where is the dirty redundant cycle wasting code like mine!?
Quintin Robinson
I spent the energy I could have spent on that, writing 'boom shaka-laka'!Almost goes without saying ;-)
kronoz
+1 for comments that make me smile.
Nescio