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


LINQ Last()用法及代碼示例

LINQ 中的 last() 方法用於返回列表/集合中的最後一個元素。如果列表/集合沒有返回元素,LINQ Last() 方法將拋出異常。

LINQ Last() 方法的語法

int result = objList.Last();

根據上述語法,我們嘗試使用 LINQ Last() 方法從 "objList" 中獲取最後一個元素。

方法語法中的 LINQ Last() 示例

這是方法語法中的 LINQ Last() 運算符的示例,用於從列表中獲取最後一個元素。

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

namespace ConsoleApp1
{
    class Program1
    {
        static void Main(string[] args)
        {
//create an array ListObj of type int store the value 1 to 5
            int[] ListObj = { 1, 2, 3, 4, 5 };
/*apply the Last() method to fetch the last element 
of the list and store in result variable of type int*/
            int result = ListObj.Last();
//Console.Writeline() used to print the value of the Last() method
            Console.WriteLine("Element from the List:{0}", result);
            Console.ReadLine();
        }
    }
}

從上麵的代碼中,我們使用 LINQ Last() 方法從 "ListObj" 列表中獲取最後一個元素。

輸出:

LINQ Last() Method

查詢語法中的 LINQ Last() 運算符示例

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

namespace ConsoleApp1
{
    class Program1
    {
        static void Main(string[] args)
        {
//create an array ListObj of type int store the value 1 to 5
            int[] ListObj = { 1, 2, 3, 4, 5 };
//apply query syntax to fetch the last value from the list
            int result = (from l in ListObj select l).Last();
            Console.WriteLine("Element from the List:{0}", result);
            Console.ReadLine();
        }
    }
}

輸出:

LINQ Last() Method



相關用法


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