个性化阅读
专注于IT技术分析

LINQ LastOrDefault()方法

本文概述

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

LINQ LastOrDefault()方法的语法

这是使用LINQ LastOrDefault()方法从列表或默认值中获取最后一个元素的语法。如果使用LINQ LastOrDefault()方法, if列表不返回任何元素。

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()方法

查询语法中的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)
        {
            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()方法

赞(0)
未经允许不得转载:srcmini » LINQ LastOrDefault()方法

评论 抢沙发

评论前必须登录!