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 = GetListOfFoosFrom开发者_如何学编程Somewhere();
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 = ?
// 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!
精彩评论