EN
C# / .NET - max value in an array
0
points
This article will show you how to find the maximum value in an array in C# / .NET.
Quick solution:
int[] array = new int[] { 1, 5, 2, 16, -5 };
int max = array.Max(); // from System.Linq
Console.WriteLine( max ); // 16
Practical examples
1. With Max() method from System.Linq.
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
int[] array = new int[] { 1, 5, 2, 16, -5 };
int max = array.Max();
Console.WriteLine( max ); // 16
}
}
2. By comparing all the elements in the array
using System;
public class Program
{
static double Max(double[] array)
{
double result = Double.NegativeInfinity;
foreach (double currentNumber in array)
{
if (result < currentNumber) result = currentNumber;
}
return result;
}
public static void Main(string[] args)
{
double[] numbersArray = new double[] { 1.4, 5.0, 2.2, 16.0, -5.0 };
Console.WriteLine( Max( numbersArray ) ); // 16
}
}