Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Dictionary<int, Enumerable> to Dictionary<int, Enumerable> inverting content

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.

like image 329
roundcrisis Avatar asked Jan 23 '23 06:01

roundcrisis


1 Answers

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));
like image 186
mmx Avatar answered Jan 27 '23 09:01

mmx