How to get the Lowest Value from a list in C#
Learn, how to get the lowest 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>() {100, 23, 40, -2, 0, 12, 3};
Now, we need to get the lowest value from a above list in C#.
Get the lowest value from a list
To get the lowest value from a list in C#, we can use the Linq Min()
method. So, It returns the lowest value from the given list.
Here is an example:
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
In the example above, we have used the Min()
method on a numsList
. So that it returns the lowest value -2
from it.
The Min() in C# returns the minimum 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 GetLowestValue {
static void Main() {
List<int> numsList = new List<int>() {};
int lowestValue = numsList.Any() ? numsList.Min() : 0;
Console.WriteLine(lowestValue);
}
}
Similarly, you can also get the highest value from a list by using the Max()
method.
using System;
using System.Linq;
using System.Collections.Generic;
class GetHighestValue {
static void Main() {
List<int> numsList = new List<int>() {100, 23, 40, -2, 0, 12, 3};
int highestValue = numsList.Max();
Console.WriteLine(highestValue);
}
}
Output:
100