I'd like to reverse keys and values of the dictionary. I.e from source dictionary Dictionary<int, string>
, I would like to get Dictionary<string, List<int>>
. There is List<int>
because the value can be in source dictionary multiple times under different keys.
Example:
{
1: "A"
2: "A"
3: "A"
4: "B"
5: "B"
6: "C"
7: "D"
}
would transform to:
{
"A": [1,2,3]
"B": [4,5]
"C": [6]
"D": [7]
}
Thanks for help.
EDIT:
OK, with help from you guys I was able to understand a bit about this algorithm. Now I see two possible solutions (among others) and don't know what is the real difference between them as the result seems to be the same.
Are there any performance issues?
var byLookup = actions.ToLookup(pair => pair.Value, pair => pair.Key)
.ToDictionary(group => group.Key, group => group.AsEnumerable());
var byGroupBy = actions.GroupBy(pair => pair.Value, pair => pair.Key)
.ToDictionary(group => group.Key, group => group.AsEnumerable());
EDIT 2:
I ended up using just
var byLookup = actions.ToLookup(pair => pair.Value, pair => pair.Key)
I didn't expected it would be this simple. Thanks all.
This is a fairly simple LINQ expression:
var res = dict
.GroupBy(p => p.Value)
.ToDictionary(g => g.Key, g => g.Select(pp => pp.Key).ToList());
First, you group by the value. This creates groups with strings as keys, and KeyValuePair<int,string>
as its items.
Then you convert the groups to a dictionary by using groups's key for the dictionary key, and "flattening" the keys of the original dictionary into a list with ToList()
.
You can also get your required result as follows:
var result = source
.GroupBy(x => x.Value, x => x.Key)
.ToDictionary(g => g.Key, g => g.ToList());
This gives the same result as dasblinkenlight, but moves the mapping of the KeyValuePair into the group by clause
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