views:

368

answers:

2

for clarity lets say we have students and classes, its a many to many relationship.

I have a Dictionary where the key is the student id and the Enumerable is a collection of classes(say we just have the id ) and I want to revert this to a Dictionary of classId, students

is there a way to do this with Linq? I can think of a way to do this with loops but I m sure there is a way to do this.

+7  A: 
var newDic = dic
   .SelectMany(pair => pair.Value
                           .Select(val => new { Key = val, Value = pair.Key }))
   .GroupBy(item => item.Key)
   .ToDictionary(gr => gr.Key, gr => gr.Select(item => item.Value));
Mehrdad Afshari
At first I thought you answered your own question. Man I'm tired.
yodaj007
+2  A: 

This should do:

var invertedDic = dic
    .SelectMany(x => x.Value, (pair, value) => new {key = pair.Key, value = value})
    .GroupBy(x => x.Value, x => x.Key, (value, key) => new {value, key})
    .ToDictionary(x => x.Value, x => x.Key);
Paul JH