Dictionary<objectx,objecty> d.我想用LINQ选择"d“中外观最多的对象y。
d.GroupBy(t => t.Value) 给了我无法从中获取值的结果。
谢谢
发布于 2012-07-18 21:26:56
objecty maxOccurenceValue = d.GroupBy(kv => kv.Value)
.OrderByDescending(g => g.Count())
.First().Key;请注意,您的对象需要覆盖Equals和GetHashCode或实现IEqualityComparer。
发布于 2012-07-18 21:24:21
你就是其中的一员。现在您有了组,您可以使用MoreLinq中的MaxBy方法来标识具有最高计数的值。
var highestFrequencyValue = d
.GroupBy(t => t.Value)
.MaxBy(g => g.Count())
.Key;implementation of MaxBy提供了一些关于您自己如何实现这一点的见解(请确保确认版权/许可)。
发布于 2012-07-18 21:53:47
或者,如果你真的只关心哪一个发生得最多(而不是它们有哪些键),那就忽略它是一个Dictionary,只对Value列表执行操作。
Dictionary<string, int> dict = new Dictionary<string, int>
{
{"hi", 3},
{"there", 3},
{"you", 4},
{"have", 5},
{"a", 5},
{"nice", 5},
{"hat", 5},
{"and", 6},
{"shoes", 6},
};
var result = dict
.Select(d => d.Value)
.GroupBy(k => k)
.OrderByDescending(k => k.Count())
.First()
.Key;
Console.WriteLine(result);
// 5编辑:我不喜欢使用第二个转换。“谢谢,”蒂姆说。修改了我的帖子,删除了他帖子里不再有的内容。
https://stackoverflow.com/questions/11542395
复制相似问题