简体   繁体   English

Chain Max 和 Where in Linq

[英]Chain Max and Where in Linq

Given this code:鉴于此代码:

Book[] books = new Book[3]
    {
        new Book("100", "Title1"),
        new Book("200", "Title2"),
        new Book("200", "Title3"),
    };

getBookWithMostPages() {
    var max = books.Max(book => book.pages);
    return books.FirstOrDefault((book) => book.pages == max);
}

Is it possible (there is any documented way) to chain Max and FirstOrDefault and return the same result?是否有可能(有任何记录的方式)链接 Max 和 FirstOrDefault 并返回相同的结果?

.NET 6 introduced the MaxBy operator. .NET 6 介绍了MaxBy算子。 I think that might be what you're looking for:我认为这可能是您正在寻找的:

var book = books.MaxBy(b => b.Pages);

Here's the implementation in the reference source so if you're using the older version of .NET you should be able to just copy it into your codebase.是参考源中的实现,因此如果您使用的是 .NET 的旧版本,您应该能够将它复制到您的代码库中。 If of course that's what you want...如果这当然是你想要的......

You can order the array and return the first value:您可以对数组进行排序并返回第一个值:

return books.OrderByDescending(book => book.pages)
            .FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM