Get Smallest and Largest Element from a List in C#



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: 2020-06-23T07:09:34+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements