Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting TKey from a dictionary with common values where TValue is List<string>

Tags:

c#

dictionary

I have a dictionary which looks like this:

Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>()
{
    {"a" , new List<string> { "Red","Yellow"} },
    {"b" , new List<string> { "Blue","Red"} },
    {"c" , new List<string> { "Green","Orange"} },
    {"d" , new List<string> { "Black","Green"} },
};

I need output as a dictionary from the dict where common value in the List<string> should be the key and the value should be the list of keys.

E.g.:

Red: [a,b]
Green: [c,d]

I don't know how to solve this problem with list in dictionary as TValue.

Please explain me how to handle lists with in dictionary.

like image 406
Watarap Avatar asked Jan 20 '26 22:01

Watarap


1 Answers

You can flattern your dictionary with SelectMany and get plain list that looks like

"a" - "Red"
"a" - "Yellow"
"b" - "Blue"
"b" = "Red"
// and so on

then group by value and build a new dictionary from those groups. Try this code:

var commonValues = dict.SelectMany(kv => kv.Value.Select(v => new {key = kv.Key, value = v}))
    .GroupBy(x => x.value)
    .Where(g => g.Count() > 1)
    .ToDictionary(g => g.Key, g => g.Select(x => x.key).ToList());
like image 181
Aleks Andreev Avatar answered Jan 22 '26 12:01

Aleks Andreev