Skip to content
On this page

获取数组中的最大值

在 C#中获取数组中的最大值可以使用 LINQ 的 Max()方法,也可以使用循环迭代数组并比较每个元素的值。下面是两种方法的示例代码:

使用 LINQ 的 Max()方法:

csharp
int[] array = { 5, 2, 10, 8, 3 };
int max = array.Max();
Console.WriteLine(max); // 输出10

使用循环迭代数组的方式:

csharp
int[] array = { 5, 2, 10, 8, 3 };
int max = array[0];
for (int i = 1; i < array.Length; i++)
{
 if (array[i] > max)
 {
     max = array[i];
 }
}
Console.WriteLine(max); // 输出10

这两种方法都可以获取数组中的最大值,但是使用 LINQ 的 Max()方法可以更简洁地实现。