如何使用LINQ选择具有最高价值的商品? [英] How do I select the item with the highest value using LINQ?

查看:151
本文介绍了如何使用LINQ选择具有最高价值的商品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,您有一个像这样的课程:

Imagine you got a class like this:

class Foo {
    string key;
    int value;
}

您如何从IEnumeralbe<Foo>中选择具有最高值的Foo?

How would you select the Foo with the highest value from an IEnumeralbe<Foo>?

一个基本问题是使迭代次数保持较低(即为1),但这会影响可读性.毕竟,我能找到的最好的方法是:

A basic problem is to keep the number of iterations low (i.e. at 1), but that affects readability. After all, the best I could find was something along the lines of this:

IEnumerable<Foo> list;
Foo max = list.Aggregate ((l, r) => l.value > r.value ? l : r);

您能想到一种更好的方法吗?

Can you think of a more better way?

list.OrderByDescending(l => l.value).First();是我的首选,但不是O(n).

list.OrderByDescending(l => l.value).First(); was my preferred option, but it is not O(n).

推荐答案

您可以获取 MoreLinq 中的cs"rel =" noreferrer> MaxBy LINQ扩展方法项目.那就是:

You can grab the MaxBy LINQ extension method from Jon Skeet's MoreLinq project. Then it's just:

Foo max = list.MaxBy(f => f.value);

这篇关于如何使用LINQ选择具有最高价值的商品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆