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() 運算符示例
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 LastOrDefault()用法及代碼示例
- LINQ AsEnumrable()用法及代碼示例
- LINQ ToLookup()用法及代碼示例
- LINQ ElementAtOrDefault()用法及代碼示例
- LINQ Count()用法及代碼示例
- LINQ Single()用法及代碼示例
- LINQ sum()用法及代碼示例
- LINQ ToArray()用法及代碼示例
- LINQ Min()用法及代碼示例
- LINQ ToDictionary()用法及代碼示例
- LINQ FirstOrDefault()用法及代碼示例
- LINQ GroupBy()用法及代碼示例
- LINQ Cast()用法及代碼示例
- LINQ ToList()用法及代碼示例
- LINQ Max()用法及代碼示例
- LINQ Aggregate()用法及代碼示例
- LINQ DefaultfEmpty()用法及代碼示例
- LINQ ElementAt()用法及代碼示例
- LINQ OfType()用法及代碼示例
- Lodash _.sampleSize()用法及代碼示例
注:本文由純淨天空篩選整理自 LINQ Last() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。