c# - 将 Dictionary<int, Enumerable> 转换为 Dictionary<int, Enumerable> 反转内容

标签 c# .net linq dictionary

为了清楚起见,假设我们有学生和类(class),这是多对多的关系。

我有一个字典,其中键是学生 ID,而 Enumerable 是一个类的集合(假设我们只有 id ),我想将其恢复为 classId、学生的字典

有没有办法用 Linq 做到这一点?我可以想出一种方法来使用循环来执行此操作,但我确信有一种方法可以执行此操作。

最佳答案

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));

关于c# - 将 Dictionary<int, Enumerable> 转换为 Dictionary<int, Enumerable> 反转内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1324912/

相关文章:

c# - 如何读取扫描支票的支票号码和银行路由号码

.net - TraceListener 页眉和页脚

c# - 如何将组中的元素拆分为多个列表?

c# - 使用 Entity Framework 的 Oracle 查询速度慢得离谱

c# - 双击文本区域或文本框时指定突出显示行为?

c# - 使 gridview 数据源保留在界面中而不是向下转换为对象

.net - Visual Basic 如何到达 %appdata%

c# - 如何处理 'The controller for path '/index' 未找到或未在 asp.net mvc 中实现 IController'?

c# - 当方法返回无效结果时我应该抛出什么异常

c# - 如何在 C# 中使用谓词来避免和或条件