Finding duplicate values in dictionary and print Key of the duplicate element

与世无争的帅哥 提交于 2019-12-18 04:44:11

问题


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.


回答1:


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);
}



回答2:


for a sample

static void Main(string[] args)
{
    Dictionary<int, int> dic = new Dictionary<int, int>();
    dic.Add(1, 1);
    dic.Add(2, 4);
    dic.Add(3, 1);
    dic.Add(4, 2);

    var result = from p in dic
                 group p by p.Value into g
                 where g.Count() > 1
                 select g;


    foreach (var r in result)
    { 
        var sameValue = (from p in r 
                        select p.Key + "").ToArray();


        Console.WriteLine("{0} has the same value {1}:",
                          string.Join("," , sameValue) , r.Key);
    }

    Console.ReadKey();
}


来源:https://stackoverflow.com/questions/7172394/finding-duplicate-values-in-dictionary-and-print-key-of-the-duplicate-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!