Home > other >  Chain Max and Where in Linq
Chain Max and Where in Linq

Time:02-12

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 ?

CodePudding user response:

.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...

CodePudding user response:

You can order the array and return the first value:

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