我有一个类型为
字典Dictionary<DateTime,double> dictionary
如何使用linq从字典中检索最小值及其对应的键?
我有一个类型为
字典Dictionary<DateTime,double> dictionary
var min = dictionary.OrderBy(kvp => kvp.Value).First();
var minKey = min.Key;
var minValue = min.Value;
虽然这种方法并不是很高效,你可能需要考虑使用MoreLinq的MinBy
扩展方法。
如果您经常执行此查询,您可能需要考虑使用不同的数据结构。
var minPair = dictionary.Aggregate((p1, p2) => (p1.Value < p2.Value) ? p1 : p2);
Aggregate
方法。MinBy
更简洁,但是使用Aggregate
可以获得更多的能力和内置功能。;) Dictionary<DateTime, double> dictionary;
//...
double min = dictionary.Min(x => x.Value);
var minMatchingKVPs = dictionary.Where(x => x.Value == min);
当然,如果你真的想在一行上完成它,你可以将其组合起来,但我认为上面的方法更易于阅读。
var minMatchingKVPs = dictionary.Where(x => x.Value == dictionary.Min(y => y.Value));
在普通的 LINQ 中,你无法轻松高效地实现这一点 - 你可以轻松获得最小值,但找到键需要再次扫描。如果你能接受这种情况,可以使用 Jess 的答案。
然而,你可能想要查看 MoreLINQ 中的 MinBy
,它让你可以这样写:
var pair = dictionary.MinBy(x => x.Value);
然后,您将拥有带有键和值的一对,仅需单次扫描即可完成。
编辑:正如Nappy所说,MinBy
也在Reactive Extensions的System.Interactive中。