Finding duplicate values in dictionary and print Key of the duplicate element(在字典中查找重复值并打印重复元素的键)
问题描述
检查字典中的重复值并打印其键的最快方法是什么?
What can be the fastest way to to check the duplicate values in the dictionary and print its key?
字典 MyDict
具有以下值,
关键价值
22 100
24 200
25 100
26 300
29 200
39 400
41 500
示例:键 22 和 25 具有相同的值,我需要打印 22 和 25 具有重复值.
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)
但是,如果您的字典或多或少是静态的,并且需要多次获取此信息,则不应只将数据保存在字典中,还应将数据保存在 ILookup
中字典的值作为键,字典的键作为值:
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);
}
这篇关于在字典中查找重复值并打印重复元素的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在字典中查找重复值并打印重复元素的键


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01