在单个LINQ查询中获取最大值和最小值 [英] Get Max and Min in a single LINQ query
本文介绍了在单个LINQ查询中获取最大值和最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组具有两个属性A和B的对象.我想获得A的最小值和B的最大值.
I have a set of objects with two properties, A and B. I'd like to get the Min of A and the Max of B.
例如
var minA = objects.Min(o => o.A);
var maxB = objects.Max(o => o.B);
使用LINQ查询语法,是否有办法做到这一点,所以它只对集合传递一次?
Using LINQ query syntax, is there a way to do this so it only passes over the set once?
期望的结果将是匿名类型(例如,results.MinA = x,results.MaxB = y)
Desired outcome would be an anonymous type (eg, results.MinA = x, results.MaxB = y)
推荐答案
Min和Max都是聚合.常规linq聚合函数为汇总
Min and Max are both aggregates. The general linq aggregate function is Aggregate
假设属性A是一个整数,而属性B是一个字符串,则可以这样写:
Assuming property A is an integer, and B is a string, you could write something like this:
objects.Aggregate(
new {
MinA = int.MaxValue,
MaxB = string.Empty
},
(accumulator, o) => new {
MinA = Math.Min(o.A, accumulator.MinA),
MaxB = o.B > accumulator.MaxB ? o.B : accumulator.MaxB
});
这篇关于在单个LINQ查询中获取最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文