How can I find the second maximum number in a list of values using Linq
and C#
?
For example I have this list:
List<double> ListOfNums = new List<double> {1, 5, 7, -1, 4, 8};
Is there a method I can get the second maximum value in the list which is 7?
var secondMax = ListOfNums.OrderByDescending(r => r).Skip(1).FirstOrDefault();
OR
var secondMax = ListOfNums.OrderByDescending(r=> r).Take(2).LastOrDefault();
just convert it to an array and take the second element
List<double> ListOfNums = new List<double> { 1, 5, 7, -1, 4, 8 };
var sndmax = ListOfNums.OrderByDescending(x => x).ToArray()[1];
Here is another way using List<T>.Sort
method:
ListOfNums.Sort();
var max = ListOfNums[1];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With