How to select a separate list of items contained in another list?

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 individual controls using linq?

The result should be:

 { contents, building, view2, view3 } 
+4
source share
3 answers

Something like that:

 var distinct = dictionary.Values.SelectMany(x => x) .Distinct(); 

I decided to leave this answer, despite the fact that Mark has an equivalent - it is instructive to see both approaches. In my approach, we take a sequence of values ​​- each of which is an IEnumerable<Control> and smooths it, saying: "For each value, we want to get an IEnumerable<Control> , just by taking this vaula."

The Marc approach takes a sequence of key / value pairs and aligns what it says: "For each pair, we want to get an IEnumerable<Control> by taking the value of the pair."

In both cases, SelectMany takes a sequence of sequences of results and aligns them into one sequence, so the result before calling Distinct() is actually a sequence { contents, building, view1, contents, view2, building, view3 } . After that, calling Distinct will give the sequence { contents, building, view1, view2, view3 } .

+4
source
 var controls = yourDictionary.SelectMany(pair => pair.Value).Distinct(); 
+6
source
 var distinctControls = dictionary.Values.SelectMany(x=>x).Distinct(); 
+1
source

All Articles