Introduction
The code snippet below will show you how to find a second largest element in an array:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MSMUTest
{
class Program
{
public int [] AcceptArrayElements(int count)
{
int[] inputElement = new int[count];
for (int cnt = 0; cnt < count; cnt++)
{
inputElement[cnt] = Convert.ToInt32(Console.ReadLine());
}
return inputElement;
}
public int FindSecondLargestElement(int[] inputElements)
{
var result = (from elements in inputElements
orderby elements descending
select elements).Distinct().Skip(1).Take(1);
#region ForBeginners
#endregion
return result.FirstOrDefault();
}
static void Main(string[] args)
{
Console.WriteLine("Please Enter Count");
int count =Convert.ToInt32( Console.ReadLine());
Program test = new Program();
Console.WriteLine("Enter Your Number");
int[] inputElements = test.AcceptArrayElements(count);
for (int cnt = 0; cnt < inputElements.Length; cnt++)
{
Console.WriteLine("Your Input Element At Position {0} is {1}.",
cnt, inputElements[cnt]);
}
Console.WriteLine("Second Largest Element In Your Provided Input Is {0} ",
test.FindSecondLargestElement(inputElements));
}
}
}