Reverse key and value in dictionary

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