在字典中查找重复值并打印重复元素的键
什么是检查字典中的重复值并打印其密钥的最快方法?
具有以下值的字典MyDict
,
关键价值
22 100
24 200
25 100
26 300
29 200
39 400
41 500
示例:键22和25具有相同的值,我需要打印22和25具有重复值。
这取决于。 如果您有一个不断更改的字典并且只需要获取该信息一次,请使用以下命令:
MyDict.GroupBy(x => x.Value).Where(x => x.Count() > 1)
但是,如果您的字典或多或少是静态的并且需要多次获取此信息,则不应仅将数据保存在字典中,而应保存在ILookup
,并将字典值作为键和键字典作为值:
var lookup = MyDict.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1);
要打印信息,您可以使用以下代码:
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); }
样品
static void Main(string[] args) { Dictionary dic = new Dictionary(); 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(); }