Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the highest and the lowest number C#

Tags:

c#

I get three values from three variables. How can i check who is the highest number and who is the lowest number?

The numbers are represented like this:

private int _score1; 
private int _score2; 
private int _score2; 

Code:

Public int Highest
{
  return the highest number here;
}

public int Lowest
{
  return the lowest number here;
}

Can i calculate the highest and the lowest number in my constructor?

like image 494
Tomten Avatar asked Nov 27 '22 18:11

Tomten


1 Answers

The obligatory Linq answer:

Public int Highest(params int[] inputs)
{
  return inputs.Max();
}

public int Lowest(params int[] inputs)
{
  return inputs.Min();
}

The beauty of this one is that it can take any number of integer inputs. To make it fail-safe you should check for a null/empty inputs array (meaning nothing was passed into the method).

To do this without Linq, you basically just have to mimic the logic performed by the extension method:

Public int Lowest(params int[] inputs)
{
   int lowest = inputs[0];
   foreach(var input in inputs)
      if(input < lowest) lowest = input;
   return lowest;
}

Again, to make it foolproof you should check for an empty or null inputs array, because calling Lowest() will throw an ArrayIndexOutOfBoundsException.

like image 109
KeithS Avatar answered Dec 18 '22 01:12

KeithS