How to get the second highest number from a array in C#
Learn, how to get the second highest number from a array in C# with the help of examples.
Consider, we have a following array of numbers in our code.
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
Now, we need to get the second highest 8
number from a above array in C#.
To get the second highest number from a array, first we need to sort the array using the Array.sort()
method then get the second highest number using the following index [myArray.Length-2]
.
Here is an example:
using System;
using System.Linq;
using System.Collections.Generic;
class GetSecondHighestNumber {
static void Main() {
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
Array.Sort(myArray);
int secondHighest = myArray[myArray.Length-2];
Console.WriteLine(secondHighest);
}
}
Output:
8
In the example above, we first sorted the array using the Array.Sort()
method by passing the array.
The Array.sort() returns the array in ascending order, so, we can get the second highest number by using the myArray[myArray.Length-2]
.
Similarly, we can also get the second highest number in C# by using the following Linq
syntax.
using System;
using System.Linq;
using System.Collections.Generic;
class GetSecondHighestNumber {
static void Main() {
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
int secondHighest = (from number in myArray
orderby number descending
select number).Skip(1).First();
Console.WriteLine(secondHighest);
}
}