Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
206 views
in Technique[技术] by (71.8m points)

c# - 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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...