Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a distinct list of elements contained in another list?

Tags:

c#

linq

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
}
like image 857
Podge Avatar asked Dec 22 '22 00:12

Podge


2 Answers

var controls = yourDictionary.SelectMany(pair => pair.Value).Distinct();
like image 189
Marc Gravell Avatar answered May 13 '23 00:05

Marc Gravell


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

like image 27
Jon Skeet Avatar answered May 13 '23 00:05

Jon Skeet