在字典中查找重复值,并打印重复元素的键 [英] Finding duplicate values in dictionary and print Key of the duplicate element

查看:770
本文介绍了在字典中查找重复值,并打印重复元素的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用最快检查字典中重复值并打印其键的方法是什么?



字典 MyDict 其具有以下值,





22 100

22 100

25 100

25 100

> 29 200



39 400 500



示例:键22和25具有相同的值,我需要打印22和25有重复的值。

解决方案

这取决于。
如果你有一个不断变化的字典,只需要得到一次,使用这个:

  MyDict.GroupBy (x => x.Value).Where(x => x.Count()> 1)


$ b b

然而,如果你有一个或多或少静态的字典,并需要不止一次获取这个信息,你不应该只是保存你的数据在字典,但也在一个 ILookup 以字典的值作为键,字典的键作为值:

  var lookup = MyDict.ToLookup(x => x.Value,x => x.Key).Where(x => x.Count()> 1); 

要打印信息,您可以使用以下代码:

  foreach(查找中的var项)
{
var keys = item.Aggregate(,(s,v)=& ,+ v);
var message =以下键具有值+ item.Key +:+ keys;
Console.WriteLine(message);
}


What can be the fastest way to to check the duplicate values in the dictionary and print its key?

Dictionary MyDict which is having following values,

Key Value

22 100

24 200

25 100

26 300

29 200

39 400

41 500

Example: key 22 and 25 have same values and i need to print that 22 and 25 have duplicate values.

解决方案

It depends. If you have an ever changing dictionary and need to get that information only once, use this:

MyDict.GroupBy(x => x.Value).Where(x => x.Count() > 1)

However, if you have a dictionary that is more or less static and need to get this information more than once, you should not just save your data in a Dictionary but also in a ILookup with the value of the dictionary as the key and the key of the dictionary as the value:

var lookup = MyDict.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1);

To print the info, you can use the following code:

foreach(var item in lookup)
{
    var keys = item.Aggregate("", (s, v) => s+", "+v);
    var message = "The following keys have the value " + item.Key + ":" + keys;
    Console.WriteLine(message);
}

这篇关于在字典中查找重复值,并打印重复元素的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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