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


LINQ LastOrDefault()用法及代碼示例

在LINQ中,LastOrDfeault()方法/運算符用於返回列表/集合中的最後一個元素,與LINQ Last()方法相同,唯一的區別是列表中沒有元素時返回默認值/收藏。

LINQ LastOrDefault() 方法的語法

下麵是使用 LINQ LastOrDefault() 方法從列表或默認值中獲取最後一個元素的語法。如果列表使用 LINQ LastOrDefault() 方法不返回任何元素。

int result = ListObj.LastOrDefault();

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

方法語法中的 LINQ LastOrDefault() 運算符示例

下麵是在方法語法中使用 LINQ LastOrDefault() 運算符從列表中獲取最後一個元素的示例。

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 having the values from 1 to 5
            int[] LISTOBJ = { 1, 2, 3, 4, 5 };
//Create another array ValObj having no values
            int[] ValObj = { };
/*LastOrDefault() method will fetch the last element 
from the LISTOBJ and store the output in the variable result*/
            int result = LISTOBJ.LastOrDefault();
/*Here LastOrDefault() method is applied on 
the ValObj array and return the result in the variable val*/
            int val = ValObj.LastOrDefault();
            Console.WriteLine("Element from the List1:{0}", result);
            Console.WriteLine("Element from the List2:{0}", val);
            Console.ReadLine();
        }
    }
}

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

輸出:

LINQ LastOrDefault() Method

查詢語法中的 LINQ LastOrDefault()operator 示例

下麵是在查詢語法中使用 LINQ LastOrDefault() 運算符從列表中獲取最後一個元素的示例。

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)
        {
            int[] LISTOBJ = { 1, 2, 3, 4, 5 };
            int[] ValObj = { };
            int result = (from l in LISTOBJ select l).LastOrDefault();
            int val = (from x in ValObj select x).LastOrDefault();
            Console.WriteLine("Element from the List1:{0}", result);
            Console.WriteLine("Element from the List2:{0}", val);
            Console.ReadLine();
        }
    }
}

輸出:

LINQ LastOrDefault() Method



相關用法


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