【发布时间】:2011-11-02 14:20:17
【问题描述】:
检查字典中的重复值并打印其键的最快方法是什么?
字典MyDict 具有以下值,
关键价值
22 100
24 200
25 100
26 300
29 200
39 400
41 500
示例:键 22 和 25 具有相同的值,我需要打印 22 和 25 具有重复值。
【问题讨论】:
标签: c# collections dictionary compare duplicates
检查字典中的重复值并打印其键的最快方法是什么?
字典MyDict 具有以下值,
关键价值
22 100
24 200
25 100
26 300
29 200
39 400
41 500
示例:键 22 和 25 具有相同的值,我需要打印 22 和 25 具有重复值。
【问题讨论】:
标签: c# collections dictionary compare duplicates
这取决于。 如果您有一本不断变化的字典,并且只需要获取一次该信息,请使用:
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);
}
【讨论】:
var lookup = MyDict.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1);。注意末尾的Where(...) 部分。
ToLookup 内部自动完成的。
样品
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();
}
【讨论】: