Ken
Ken

Reputation: 5224

How to get only the unique values out of a list of strings 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.

Upvotes: 4

Views: 1415

Answers (2)

ljs
ljs

Reputation: 37847

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!

Upvotes: 6

Quintin Robinson
Quintin Robinson

Reputation: 82375

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

strings = strings.Distinct().ToList();

Upvotes: 10

Related Questions