C# Program to get the smallest and largest element from a list


Set a list.

List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };

To get the smallest element, use the Min() method.

list.AsQueryable().Min();

To get the largest element, use the Max() method.

list.AsQueryable().Max();

Let us see the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
   static void Main() {
      List<long> list = new List<long> { 150, 300, 400, 350, 450, 550, 600 };
      foreach(long ele in list){
         Console.WriteLine(ele);
      }

      // getting largest element
      long max_num = list.AsQueryable().Max();

      // getting smallest element
      long min_num = list.AsQueryable().Min();

      Console.WriteLine("Smallest number = {0}", min_num);
      Console.WriteLine("Largest number = {0}", max_num);
   }
}

Output

150
300
400
350
450
550
600
Smallest number = 150
Largest number = 600

Updated on: 23-Jun-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements