I have the following code
new Dictionary<string,IEnumerable<Control>>()
{
{ "view1", new Control[] { contents, building, view1 }},
{ "view2", new Control[] { contents, view2 }},
{ "view3", new Control[] { building, view3 }
}
How do I get a list of all the distinct controls using linq?
The result should be:
{
contents,
building,
view2,
view3
}
var controls = yourDictionary.SelectMany(pair => pair.Value).Distinct();
Something like this:
var distinct = dictionary.Values.SelectMany(x => x)
.Distinct();
I've decided to keep this answer despite Marc having an equivalent one - it's instructive to see both approaches. In my approach we take the sequence of values - each of which is an IEnumerable<Control>
and flatten it by saying, "For each value, we want to obtain an IEnumerable<Control>
just by taking that vaule."
Marc's approach takes the sequence of key/value pairs and flattens that saying, "For each pair, we want to obtain an IEnumerable<Control>
by taking the value of the pair."
In both cases, SelectMany
takes the sequence of result sequences, and flattens them into a single sequence - so the result before the Distinct()
call is effectively the sequence { contents, building, view1, contents, view2, building, view3 }
. The Distinct
call will then yield the sequence { contents, building, view1, view2, view3 }
.
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