C#:如何比较字典值?
我有一个 Dictionary
如下
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
这里所有具有相同值的
是我生成的字典
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());
上面的代码将产生类似的结果
{ "A" { "A" , "D", "F" } }
{ "B" { "B" , "E" } }
{ "C" { "C" } }
{ "D" { "A" , "D", "F" } }
{ "E" { "B" , "E" } }
{ "F" { "A" , "D", "F" } }
但我的解决方案有两个问题
存在重复值列表(对于键
D
,E
和F
。)值列表包含密钥。
预期输出就像
{ "A" { "D", "F" } }
{ "B" { "E" } }
不需要key C
,因为C
的值在任何地方都不会重复。
并且不需要包含键 D 、 E 和 F
,因为它已经包含在 A
和 B
的值列表中。
如何使用 Linq
或 Lambda 表达式
执行此操作?
I have a Dictionary<String,String>
as follows
Dictionary<String, String> MyDict = new Dictionary<String, String>();
and which contains
MyDict.Add("A", "1010");
MyDict.Add("B", "1011");
MyDict.Add("C", "1110");
MyDict.Add("D", "1010");
MyDict.Add("E", "1011");
MyDict.Add("F", "1010");
I need to Compare the Dictionary Values
and then to add the key
s which all having same values
here is My resulting Dictionary
Dictionary<String, List<String>> MyResultDict = new Dictionary<String, List<String>>();
And My code
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
There exist Duplicate value list ( for the keys
D
,E
andF
.)The Value List includes the key.
The Expected OutPut is like
{ "A" { "D", "F" } }
{ "B" { "E" } }
i.e There is no need of key C
because C
's value is not repeated anywhere.
and there is no need to include keys D , E and F
because its already included in A
's and B
's value lists.
How to do this using Linq
or Lambda Expression
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者可能更简单一点:
or possibly a bit simpler:
这应该可以做到:
这里的关键(如果您能原谅这个双关语)是 GroupBy 方法 - 它根据您的比较将枚举元素收集在一起。完成此操作后,删除单例并将剩余元素转换为新字典就很简单了。
This should do it:
The key here (if you'll forgive the pun) is the GroupBy method - it collects together elements of an enumeration based on your comparison. Once you've done that, it's a simple case of removing the singletons and converting the remaining elements to a new Dictionary.