How to get the Maximum Value from a list in C#
Learn, how to get the maximum value from a list in C# with the help of examples.
Consider, we have a following list in our code.
List<int> numsList = new List<int>() {10, 23, 400, -2, 0, 12, 3};
Now, we need to get the maximum value from a above list in C#.
Get the Maximum value from a list
To get the maximum value from a list in C#, we can use the built-in Linq Max()
method. So, It returns the maximum value from the given list.
Here is an example:
using System;
using System.Linq;
using System.Collections.Generic;
class GetMaximumValue {
static void Main() {
List<int> numsList = new List<int>() {10, 23, 400, -2, 0, 12, 3};
int maxValue = numsList.Max();
Console.WriteLine(maxValue);
}
}
Output:
400
In the example above, we have used the Max()
method on a numsList
. So, it returns the Maximum value 400
from it.
The Max() in C# returns the maximum value from the sequence of values.
The above method only works if the list is not empty. So, if a user passes an empty list we can return a value 0
instead of error InvalidOperationException
in terminal with the help of Any()
method.
using System;
using System.Linq;
using System.Collections.Generic;
class GetMaximumValue {
static void Main() {
List<int> numsList = new List<int>() {};
int maxValue = numsList.Any() ? numsList.Min() : 0;
Console.WriteLine(maxValue);
}
}
Output:
0
Similarly, you can also get the lowest value from a list by using the Min()
method in C#.
using System;
using System.Linq;
using System.Collections.Generic;
class GetLowestValue {
static void Main() {
List<int> numsList = new List<int>() {100, 23, 40, -2, 0, 12, 3};
int lowestValue = numsList.Min();
Console.WriteLine(lowestValue);
}
}
Output:
-2