Microsoft made a couple new additions to LINQ as part of the C# 13 / .NET 9 release a few weeks ago, and, since I happen to really like LINQ, I wrote about how to use them. That got me thinking about other recent additions I might’ve missed in the last few releases, so I started looking back. And whatdya know, we got a slew of updates to LINQ in C# 10 / .NET 6 a few years ago.
Let’s take a look at two of them - MaxBy and MinBy - right after a brief overview of what we had before. Makes it a little easier to appreciate the new stuff!
The code in this post is available on GitHub, for you to use, extend, or just follow along while you read… and hopefully discover something new along the way!
Finding a Simple ‘Max’
Normally, when we want to find the max or min value of some collection of primitive types, then a simple call to Max or Min will do. With a list of integers, for example, the max number is the highest. No surprise there.
| |
Finding the max value in a list of integers
Implementing IComparer<T>
For other types, we can implement the IComparer<T> interface, telling Max and Min what to use for the comparison. It can be really complex, or as simple as looking at one property:
| |
Employee record, implementing IComparable<T>
In this case, the max or min Employee is just whoever makes the most or least:
| |
Using MinBy and MaxBy
The new *MaxBy* and *MinBy* methods let us specify a property to sort by, which allows for more flexbility in simple cases. We can sort employees by hire date, for example, and then sort by their security level immediately after:
| |
Before, if we weren’t implementing the interface, then we had to order the collection first and grab the first item, like this:
| |
That isn’t much longer, but MaxBy and MinBy just read better. The new methods make it easier to tell at a glance what the code is doing, and that’s not a trivial thing. We don’t have to reason out what the OrderBy is doing, nor do we have to open the class and investigate the CompareTo method.
Like anything though, there’s limitations. Since we can only specify one property, we still need something like this to consider multiple properties:
| |
We can also use methods that provide a useful value, like the Count() method on a collection. One more example and then I’m done! Here’s two companies, and a quick use of MaxBy to grab the one with more employees:
| |
I, for one, welcome any and all additions to LINQ, and can imagine that in many situations MaxBy and MinBy will make the code we write a little cleaner. Every bit counts!
Learning More
If you found this content useful, and would like to learn more about a variety of C# features, check out my CSharpDotNetFeatures repo, where you’ll find links to plenty more blog posts and practical examples!
