Select distinct values in all nested collections using LINQ to objects?

Brian Vallelunga picture Brian Vallelunga · Oct 14, 2009 · Viewed 10.5k times · Source

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 = ?

Answer

Vitaliy picture Vitaliy · Oct 14, 2009
 // 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!