Claudio Ferraro
Claudio Ferraro

Reputation: 4721

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 ?

Upvotes: 1

Views: 81

Answers (2)

Jannik
Jannik

Reputation: 61

You can sort the array and return the first value:

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

Upvotes: 2

TKharaishvili
TKharaishvili

Reputation: 2099

.NET 6 introduced the MaxBy operator. 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. If of course that's what you want...

Upvotes: 4

Related Questions