在字典中查找重复值并打印重复元素的键

San*_*ile 9 c# collections dictionary compare duplicates

什么是检查字典中的重复值并打印其密钥的最快方法?

MyDict具有以下值的字典,

关键 价值

22 100

24 200

25 100

26 300

29 200

39 400

41 500

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

Dan*_*rth 23

这取决于.如果您有一个不断变化的字典并且只需要获取该信息一次,请使用:

MyDict.GroupBy(x => x.Value).Where(x => x.Count() > 1)
Run Code Online (Sandbox Code Playgroud)

但是,如果您的字典或多或少是静态的并且需要多次获取此信息,则不应仅将数据保存在字典中,而应将字典ILookup值作为键和密钥保存在字典中.字典作为值:

var lookup = MyDict.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1);
Run Code Online (Sandbox Code Playgroud)

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

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);
}
Run Code Online (Sandbox Code Playgroud)


she*_*bin 5

样品

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();
}
Run Code Online (Sandbox Code Playgroud)