C#:如何比较字典值? [英] C# : How to compare Dictionary Values?

查看:109
本文介绍了C#:如何比较字典值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dictionary<String,String>如下

 Dictionary<String, String> MyDict = new Dictionary<String, String>();

其中包含

 MyDict.Add("A", "1010");
 MyDict.Add("B", "1011");
 MyDict.Add("C", "1110");
 MyDict.Add("D", "1010");
 MyDict.Add("E", "1011");
 MyDict.Add("F", "1010");

我需要比较字典Values,然后添加所有具有相同值的key

I need to Compare the Dictionary Values and then to add the keys which all having same values

这是我生成的词典

 Dictionary<String, List<String>> MyResultDict = new Dictionary<String, List<String>>();

我的代码

 var XXX = MyDict.ToLookup(X => X.Value, X => X.Key);
 MyResultDict = MyDict.ToDictionary(X => X.Key, X => XXX[X.Value].ToList());

上面的代码将产生类似的结果

The above code will produce the result like

 { "A"     { "A" , "D", "F" } }
 { "B"     { "B" , "E" } }
 { "C"     { "C" } }
 { "D"     { "A" , "D", "F" } }
 { "E"     { "B" , "E" } }
 { "F"     { "A" , "D", "F" } }

但是我的解决方案有两个问题

But my solution is having two problem

  1. 存在重复的值列表(用于键DEF.)

值列表包含键.

预期输出就像

 { "A"     { "D", "F" } }
 { "B"     { "E" } }

i.e不需要key C,因为C的值不会在任何地方重复.

i.e There is no need of key C because C's value is not repeated anywhere.

,并且不需要包含keys D , E and F,因为它已经包含在AB的值列表中.

and there is no need to include keys D , E and F because its already included in A's and B's value lists.

如何使用LinqLambda Expression执行此操作?

How to do this using Linq or Lambda Expression?

推荐答案

Dictionary<string, List<string>> result = myDict
    .GroupBy(kvp => kvp.Value)
    .Select(grp => new { Key = grp.First().Key, Matches = grp.Skip(1).Select(k => k.Key).ToList() })
    .Where(m => m.Matches.Count > 0)
    .ToDictionary(m => m.Key, m => m.Matches);

或者可能更简单一些:

Dictionary<string, List<string>> result = myDict
    .GroupBy(kvp => kvp.Value)
    .Where(grp => grp.Count() > 1)
    .ToDictionary(grp => grp.First().Key, grp => grp.Skip(1).Select(k => k.Key).ToList());

这篇关于C#:如何比较字典值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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