MaxBy and MinBy: New LINQ extensions series

Linq MaxBy and MinBy

MaxBy and MinBy are both part of .NET 6. Since .NET 6 is released recently, it is a good opportunity to mention some of the new LINQ extensions methods. I will post a series of small articles focused on some these new or maybe less known LINQ methods.

In this article I am going to take MaxBy and MinBy LINQ method with some examples so it is easier to understand it.

Prerequisites

To to use these new LINQ extensions you need to download and install this version of .NET 6.

I download and install Visual Studio 2022 in this article.

MaxBy and MinBy

MaxBy Returns the maximum value in a generic sequence according to a specified key selector function and key comparer.

MinBy Returns the minimum value in a generic sequence according to a specified key selector function and key comparer.

Example

For this example we will create a model called GameWinner:

public class GameWinner
{
    public GameWinner(string name, int rank, int point)
    {
        Name = name;
        Rank = rank;
        Point = point;
    }

    public string Name { get; set; }
    public int Rank { get; set; }
    public int Point { get; set; }
}

Lets now create a list of winners:

var gameWinners = new List<GameWinner>
{
    new ("John", 1, 99),
    new ("Peter", 3, 95),
    new ("Mick", 2, 96)
};

and try to get the first winner and the third winner:

var highestPoint = gameWinners.MaxBy(e => e.Point);
var lowestPoint = gameWinners.MinBy(e => e.Point);

Now lets print the results:

Console.WriteLine($"{highestPoint?.Name} has highest point {highestPoint?.Point}");
Console.WriteLine($"{lowestPoint?.Name} has highest point {lowestPoint?.Point}");

Lets see the output:

John has highest point 99
Peter has highest point 95

Download my examples form GitHub.

Microsoft MinBy documentation and MaxBy documentation

Leave a Reply

Your email address will not be published. Required fields are marked *