Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the Second Max in a list of values using linq c#

Tags:

c#

linq

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?

like image 490
Vahid Avatar asked Apr 04 '14 20:04

Vahid


3 Answers

var secondMax = ListOfNums.OrderByDescending(r => r).Skip(1).FirstOrDefault();

OR

var secondMax = ListOfNums.OrderByDescending(r=> r).Take(2).LastOrDefault();
like image 83
Habib Avatar answered Sep 28 '22 13:09

Habib


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]; 
like image 27
BRAHIM Kamel Avatar answered Sep 28 '22 15:09

BRAHIM Kamel


Here is another way using List<T>.Sort method:

ListOfNums.Sort();
var max = ListOfNums[1];
like image 28
Selman Genç Avatar answered Sep 28 '22 15:09

Selman Genç