Linq:如何对集合中所有对象的属性执行.max(),并返回最大值[的对象我有一个有两个int属性的对象列表。该列表是另一个Linq查询的输出。对象:public class DimensionPair {
public int Height { get; set; }
public int Width { get; set; }}我想在列表中找到并返回其中最大的对象Height财产价值我可以设法获得最高值的Height值,而不是对象本身。我能和Linq一起做这个吗?多么,怎样?
3 回答

皈依舞
TA贡献1851条经验 获得超3个赞
var item = items.MaxBy(x => x.Height);
MaxBy
):
它是O(N)不像 ,它在每次迭代中找到最大值(使其为O(n^2)。 排序解为O(N Logn) 拿着 Max
值,然后找到带有该值的第一个元素是O(N),但在序列上迭代两次。在可能的情况下,您应该以单程方式使用LINQ。 与聚合版本相比,阅读和理解要简单得多,并且每个元素只计算一次投影

萧十郎
TA贡献1815条经验 获得超13个赞
var maxObject = list.OrderByDescending(item => item.Height).First();
list
list
List<T>
IEnumerable<T>
MaxObject
static class EnumerableExtensions { public static T MaxObject<T,U>(this IEnumerable<T> source, Func<T,U> selector) where U : IComparable<U> { if (source == null) throw new ArgumentNullException("source"); bool first = true; T maxObj = default(T); U maxKey = default(U); foreach (var item in source) { if (first) { maxObj = item; maxKey = selector(maxObj); first = false; } else { U currentKey = selector(item); if (currentKey.CompareTo(maxKey) > 0) { maxKey = currentKey; maxObj = item; } } } if (first) throw new InvalidOperationException("Sequence is empty."); return maxObj; }}
var maxObject = list.MaxObject(item => item.Height);
- 3 回答
- 0 关注
- 2981 浏览
添加回答
举报
0/150
提交
取消