views:

844

answers:

1

Given the following code setup:

public class Foo {
 List<string> MyStrings { get; set; }
}

List<Foo> foos = GetListOfFoosFromSomewhere();

How do I get a list of all of the distinct strings in MyStrings across all of the Foo instances using LINQ? I feel like this should be easy, but can't quite figure it out.

string[] distinctMyStrings = ?
+3  A: 
 // If you dont want to use a sub query, I would suggest:

        var result = (
            from f in foos
            from s in f.MyStrings
            select s).Distinct();

        // Which is absoulutely equivalent to:

        var theSameThing = foos.SelectMany(i => i.MyStrings).Distinct();

        // pick the one you think is more readable.

I also strongly recommend reading the MSDN on the Enumerable extension methods. It is very informative and has great examples!

Vitaliy