當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


LINQ Max()用法及代碼示例

LINQ 中的 max() 函數用於返回集合中的最大值。借助 Max() 函數,可以很容易地使用 Max() 函數從給定的數據源中找到最大值。在另一種情況下,我們必須編寫代碼以從值列表中獲取最大值。

下麵是在 C# 中使用 LINQ Max() 函數從列表或集合中獲取最大值的語法。

C#中的LINQ Max()函數語法

int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int MaximumNum = a.Max();

觀察上述語法後,我們正在使用 LINQ Max() 函數從 "a" 列表中獲取最大值。

例:在此示例中,我們使用 Max() 函數從 C# 中的數組值列表中獲取最大值。

using System;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
//Create an array named 'a' type of int having the values 1 t 9
            int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            Console.WriteLine("The Maximum value in the array is:");
/*Max() function is applied on the array to 
find the maximum value from the arra*/
            int maximumNum = a.Max();

            Console.WriteLine("The maximum Number is {0}", maximumNum);

            Console.ReadLine();
        }
    }
}

輸出

從上麵的例子中,它將顯示整數數組 "a,",我們正在使用 LINQ Max() 函數從給定的數組中找到最大值。

現在我們運行應用程序,它將顯示列表中的最大值,如下所示在控製台窗口的輸出中。

LINQ Max() Function



相關用法


注:本文由純淨天空篩選整理自 LINQ Max() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。