Linq Min and Max c# example

Min and max are in-built function in LINQ, very useful when we want to find min value or max value of any numeric column.

Remember, If you try to perform max or min function on an empty collection then the query will throw exception

var _numbers = new List<int>();  // empty list
int maxNumber = _numbers.Max();  // this will throws InvalidOperationException

Notice, when we try to find max value of empty list that will throw exception, however, the null value is accepted, if we use null in our list, then try to find min value, that will work perfectly!

var numbers = new List<int?> { 10, 75, null, 30, 45, 87 };
int? minNumber = numbers.Min();  // minNumber: 10

See the result of above code, the min value is 10 not null, but null will not cause any error.

Find Max value in LINQ query

Here with each example we find max value and min value from same list collection object in linq query.

var _numbers = new List<int> { 12, 9, 4, 7, 10, 40, 90, 2 };
int maxNumber = _numbers.Max();  // maxNumber: 90
int minNumber = _numbers.Min();  // minNumber: 2

See in above query we found the min value 2 from linq query.

LINQ Max with Selector

We can use max or min function with linq select query.

Here we try to find value of string length, first using selector then using max function, both will give same result.

var stringList = new List<string> { "1", "1234567890", "123", "12" };

// both lines give same output
int maxLength1 = stringList.Select(x => x.Length).Max();  // maxLength: 10
int maxLength2 = stringList.Max(x => x.Length);           // maxLength: 10

LINQ Max on custom object property

Now we see how to use max function on custom object property, for example we want to find max score of student from our student list object.

First we create a student list object with different values, then find the max score of student using linq query.

var student = new List<Student>();
student.Add(new Student() { Firstname = "John", Score= 70});
student.Add(new Student() { Firstname = "Ajay", Score = 82 });
student.Add(new Student() { Firstname = "Ruby", Score = 60 });
student.Add(new Student() { Firstname = "Archana", Score = 65 });

int? maxScore=  student.Max(p => p.Score);

Console.WriteLine(maxScore); // result 82
Linq Max Query Syntax

The same above max function we can also use in linq query syntax.

var list = new List<int> { 10, 45, 21, 66, 85, 56 };
int maxNumber = (from x in list select x).Max();
Console.WriteLine(maxNumber);// maxNumber: 85

You may be also interested to learn how to use Max with GroupBy in LINQ query.

LINQ Max and Min Example
LINQ (language integrated query) allow you to write query on database objects like, entity framework etc, LINQ is type safe, easy to convert database object to list objects and business objects in secure and scalable way.
linq Interview Questions Answers
LINQ C# examples | Join MVC Course