4

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.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
roundcrisis
  • 17,276
  • 14
  • 60
  • 92

2 Answers2

7
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
  • 414,610
  • 91
  • 852
  • 789
2

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
  • 56
  • 2