Reverse many-to-many Dictionary>

前端 未结 3 1883
再見小時候
再見小時候 2021-02-05 05:41

Actually my previous question got me thinking and I realized that reversing a Dictionary is not trivial. What is the most elegant and readable way to do it?

3条回答
  •  离开以前
    2021-02-05 05:50

    I'm not sure exactly how this differs from your previous question.

    If you're just asking how to return a Dictionary> rather than Dictionary> then all you need is a call to the ToList method.

    Stealing and amending Mehrdad's answer to your other question:

    var classToStudent = studentToClass
        .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).ToList());
    

提交回复
热议问题