反向多到很多词典和LT;键,列表与LT;价值>> [英] Reverse many-to-many Dictionary<key, List<value>>

查看:108
本文介绍了反向多到很多词典和LT;键,列表与LT;价值>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前面的问题让我想起了
和我意识到,扭转了词典是不平凡的。
什么是最优雅,最可读的方式做到这一点?

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?

同样的情景学生多对多带类

Same scenario student Many to Many with Classes

Dicitonary< INT,列表与LT; INT>> ,其中最关键的是studentId和值是列表< INT> 包含的classId,想要恢复到词典<的classId,列表与LT; studentId>>

original Dicitonary<int, List<int>> where the key is studentId and the Value is a List<int> that contains classId and want to revert to Dictionary<classId, List<studentId>>

感谢

更新:
其实我只是测试卢克和布鲁诺的解决方案,他们返回归类谁,他们都具有相同的学生适量,将更新为我走。

Update: Actually I just tested Luke and Bruno's solutions and they return the right amount of classed whoever they all have the same student, will update as i go along.

推荐答案

稍微不同的方式(更理解我的大脑有点反正:) ...

Slightly different way (a bit more comprehensible to my brain anyway :) ...

var newDict = new Dictionary<int, List<int>>();
var dict = new Dictionary<int, List<int>>();
dict.Add( 1, new List<int>() { 1, 2, 3, 4, 5 } );
dict.Add( 2, new List<int>() { 1, 2, 3, 4, 5 } );
dict.Add( 3, new List<int>() { 1, 2, 6 } );
dict.Add( 4, new List<int>() { 1, 6, 7 } );
dict.Add( 5, new List<int>() { 8 } );

var newKeys = dict.Values.SelectMany( v => v ).Distinct();

foreach( var nk in newKeys )
{
   var vals = dict.Keys.Where( k => dict[k].Contains(nk) );
   newDict.Add( nk, vals.ToList() );
}

这篇关于反向多到很多词典和LT;键,列表与LT;价值&GT;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆