Here we are going to find the 2nd largest number from a collection which is an array using LINQ.
The approach is to sort the array in order of descending then skip the items to the count of Nth – 1 and take the first element. You can add code to take input from user as well.
In order to execute the code I’ve created a simple console application to print out the result.
Please find complete code below:
using System;
using System.Linq;
namespace PracticeConsole
{
class Program
{
static void Main(string[] args)
{
int[] findNthLargestNumberFromArray = { 1, 4, 2, 9, 7, 6 };
int largestNumber = 2;
int secondLargest = findNthLargestNumberFromArray.OrderByDescending(x => x).Skip(largestNumber - 1).First();
Console.WriteLine(secondLargest);
Console.ReadLine();
}
}
}
The console output will print out result as 7.