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 = ?
// 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With