LINQ中的last()方法用于返回列表/集合中的最后一个元素。如果列表/集合没有返回任何元素,Linq Last()方法将抛出异常。
LINQ Last()方法的语法
int result = objList.Last();
From the above syntax, we are trying to fetch the last element from the "objList" using LINQ Last () method.
方法语法中的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(); } } }
From the above code, we are getting the last element from the "ListObj" list by using the 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(); } } }
输出:
