Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 = ?
like image 628
Brian Vallelunga Avatar asked Oct 14 '09 19:10

Brian Vallelunga


1 Answers

 // 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!

like image 181
Vitaliy Avatar answered Oct 10 '22 12:10

Vitaliy