LastOrDefault()方法

LastOrDefault()方法 首页 / LinQ入门教程 / LastOrDefault()方法

在LINQ中,LastOrDfeult()方法/运算符用于返回列表/集合中的最后一个元素,与LINQ Last()方法相同,唯一不同的是当列表/集合中没有元素时返回默认值。

LINQ LastOrDefault()方法的语法

下面是使用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.

方法语法中的LINQ LastOrDefault()运算符示例

下面是在方法语法中使用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.

输出:

LINQ LastOrDefault() Method

查询语法中的LINQ LastOrDefault()运算符示例

下面是在查询语法中使用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();
        }
    }
}

输出:

LINQ LastOrDefault() Method




祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入拆解Java虚拟机 -〔郑雨迪〕

软件工程之美 -〔宝玉〕

用户体验设计实战课 -〔相辉〕

网络排查案例课 -〔杨胜辉〕

大厂广告产品心法 -〔郭谊〕

后端工程师的高阶面经 -〔邓明〕

AI绘画核心技术与实战 -〔南柯〕

PPT设计进阶 · 从基础操作到高级创意 -〔李金宝(Bobbie)〕

AI 应用实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)