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

LINQ Last()方法

本文概述

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

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

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

评论 抢沙发

评论前必须登录!