4

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.

2 Answers 2

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

strings = strings.Distinct().ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

but dude... no boom shaka-laka?!
You see I just like BOOOM! But I wasn't sure if I should.. =P
6

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!

2 Comments

You and your verbose examples, where is the dirty redundant cycle wasting code like mine!?
I spent the energy I could have spent on that, writing 'boom shaka-laka'! Almost goes without saying ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.