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.
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());
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