tags:

views:

93

answers:

3
+3  Q: 

c# linq distinct

Hello,
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 so it contains
contents, building, view1, view2, view3.

Thanks in advance

Podge

+2  A: 
var controls = yourDictionary.SelectMany(pair => pair.Value).Distinct();
Marc Gravell
Marc Gravell vs Jon Skeet, what a battle! :)
Andrey
@Andrey - even *if* I occasionally win the odd "battle", I think we know who owns the war ;p
Marc Gravell
+2  A: 

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 }.

Jon Skeet
Well, if you're going to go and *explain* things ;p My reasoning is that maybe the pair approach has less indirection (via `ValueCollection` etc). But either will work.
Marc Gravell
Thanks everybody, I have given Jon the credit as he explained it, as I cannot determine who posted first. Sorry Marc. Podge
Podge
+1  A: 
var distinctControls = dictionary.Values.SelectMany(x=>x).Distinct();
Mark Cidade