0 Comments Posted in:

The third video in my Exploring MoreLINQ series looks at the MinBy and MaxBy methods, which allow you to find the items in a collection that are the "maximum" or "minimum" according a criteria you specify. This is really useful method when the built-in Max or Min methods in LINQ aren't quite what you need.

For example, say we have an IEnumerable<Book> and we wanted to find which book has the most pages, LINQ's Max method would tell us what the maximum PageCount was, but wouldn't tell us which book had that number of pages. MoreLINQ's MaxBy method gives us what we want - it finds the book(s) that have the maximum number of pages.

Obviously there could be multiple books with the maximum numbers which is why it returns an IEnumerable<T> so you may want to follow it up with a call to First like this:

IEnumerable<Book> books = GetBooks();
var mostPages = books.Max(b => b.PageCount); // just finds the highest page count
var longestBook = books.MaxBy(b => b.PageCount).First(); // finds the first book with the highest page count

For another real-world example of where MaxBy is useful - check out my solution to one of the Advent of Code problems where I have to find the seating plan with maximum happiness.

You can find all videos in this series here.

Want to learn more about LINQ? Be sure to check out my Pluralsight course More Effective LINQ.
Vote on HN