How can I choose the second highest value from a list in c#?

  • A+
Category:Languages

I have a list List<int> myList = new List<int>() { 10, 20, 8, 20, 9, 5, 20, 10 };, I want to choose the second highest value, which is in this case 10. I wrote this code and it works, but I wonder if there is something shorter and better.

List<int> myList = new List<int>() { 10, 20, 8, 20, 9, 5, 20, 10 }; myList = myList.Distinct().ToList(); var descendingOrder = myList.OrderByDescending(i => i); var sec = descendingOrder.Skip(1).First(); 

 


You could just stop using intermediate variables and ToList()

var secondHighest =      myList     .Distinct()     .OrderByDescending(i => i);     .Skip(1)     .First(); 

This will work the same as your version, but only requires one statement instead of three.

I find it a lot easier to read code list this.

Each LINQ method call on it's own line, and no intermediate variables, especially ones that change (myList is reassigned, which makes it harder to comprehend).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: