在LINQ中,LastOrDfeult()方法/运算符用于返回列表/集合中的最后一个元素,与LINQ Last()方法相同,唯一不同的是当列表/集合中没有元素时返回默认值。
下面是使用LINQLastOrDefault()方法从列表或默认值获取最后一个元素的语法。如果使用LINQ LastOrDefault()方法,IF List不返回任何元素。
int result = ListObj.LastOrDefault();
From the above syntax, we are trying to get the last element from the "LastObj" list using LINQ LastOrDefault() method.
下面是在方法语法中使用LINQLastOrDefault()运算符从列表中获取最后一个元素的示例。
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(); } } }
From the above code, we are getting the last element from "LISTOBJ" and "ValObj" lists by using the LINQ LastOrDefault() method.
输出:
下面是在查询语法中使用LINQLastOrDefault()运算符从列表中获取最后一个元素的示例。
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(); } } }
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
PPT设计进阶 · 从基础操作到高级创意 -〔李金宝(Bobbie)〕