C# program to find Largest, Smallest, Second Largest, Second Smallest in a List

CsharpProgrammingServer Side Programming

Set the list

var val = new int[] {
   99,
   35,
   26,
   87
};

Now get the largest number.

val.Max(z => z);

Smallest number

val.Min(z => z);

Second largest number

val.OrderByDescending(z => z).Skip(1).First();

Second smallest number

val.OrderBy(z => z).Skip(1).First();

The following is the code −

Example

 Live Demo

using System;
using System.Linq;

public class Program {
   public static void Main() {
      var val = new int[] {
         99,
         35,
         26,
         87
      };

      var maxNum = val.Max(z => z);
      Console.WriteLine("Maximum Number: " + maxNum);

      var minNum = val.Min(z => z);
      Console.WriteLine("Minimum Number: " + minNum);

      var secondMax = val.OrderByDescending(z => z).Skip(1).First();
      Console.WriteLine("Second Largest Number: " + secondMax);

      var secondMin = val.OrderBy(z => z).Skip(1).First();
      Console.WriteLine("Second Smallest Number: " + secondMin);
   }
}

Output

Maximum Number: 99
Minimum Number: 26
Second Largest Number: 87
Second Smallest Number: 35
raja
Published on 21-Aug-2018 11:10:17
Advertisements