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

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 1264
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 };
double minNum = 0;
double maxNum = 0;

minNum = lstNumbers[0];
maxNum = lstNumbers[0];
for(int i = 1;i< lstNumbers.Count;i++){
//logic for obtaining the Minimum Number
if (minNum > lstNumbers[i]) minNum = lstNumbers[i];

//logic for obtaining the Maximum Number
if (maxNum < lstNumbers[i]) maxNum = lstNumbers[i];
}
Console.WriteLine("Min = {0} , Max = {1}", minNum, maxNum);
Console.ReadKey(true);
}
}
}

Hope this will be helpful.

Comments or Responses

Posted by: Asutosha on: 10/26/2015 Level:Starter | Status: [Member] | Points: 10
Is there any option you could use LINQ with lambda Expression instead of for loop ?
Posted by: Rajnilari2015 on: 10/26/2015 Level:Platinum | Status: [Member] [Microsoft_MVP] [MVP] | Points: 10
Easy way is to use MAX and MIN function. No need for LINQ/Lambda (: You can also check my other solutions for the same.
Posted by: Rajnilari2015 on: 10/30/2015 Level:Platinum | Status: [Member] [Microsoft_MVP] [MVP] | Points: 10
@Asutosha, Kindly have a look at the other solutions provided by me http://www.dotnetfunda.com/forums/show/20734/can-any-one-help-me-for-these-basic-programs

Login to post response