Find a Nth highest or lowest number in a given series of numbers - Solution2

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 254
Suppose we have a collection of numbers (+ve, -ve, fractional) and we need to find out the MAX and MIN from that. The below code will help to do so

using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

List<double> lstNumbers = new List<double>() { 1, 2.06, 34, -4, 5.90, 61.9, 7.8, 8, 9, 18.0,23.7 };
var sortedNumbers = lstNumbers.OrderBy(o => o).ToList();
double minNum = sortedNumbers.First();
double maxNum = sortedNumbers.Last();
Console.WriteLine("Min = {0} , Max = {1}", minNum, maxNum);
Console.ReadKey(true);
}
}

}


Here we are using OrderBy for sorting and then apply the First() and Last() Extension Methods of Enumerable Class that resides under the namespace System.Linq to accomplish the operation.
Hope this will be helpful.

Comments or Responses

Login to post response