本文介绍了转换字典< INT,可枚举>到词典< INT,可枚举>反相内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了清楚起见,可以说,我们有学生和类,它是一个多对多的关系。
我有一个字典,其中的关键是学生证和可枚举是类(比方说,我们只是有ID)的集合,我想要恢复这的classId的字典,学生
是有办法的LINQ做到这一点?我能想到的方法来与循环做到这一点,但我敢肯定是有办法做到这一点。
解决方案
VAR newDic = DIC
.SelectMany(双=> pair.Value
。选择(VAL =>新建{键= VAL,值= pair.Key}))
.GroupBy(项目=> item.Key)
.ToDictionary(GR => gr.Key,GR => gr.Select(项目=> item.Value));
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.
解决方案
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));
这篇关于转换字典< INT,可枚举>到词典< INT,可枚举>反相内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!