LINQ First()元素

LINQ First()元素 首页 / LinQ入门教程 / LINQ First()元素

在LINQ中,first()方法/运算符用于根据指定的条件返回列表或集合中的项序列中的第一个元素或列表中项序列中的第一个元素。如果基于指定条件的列表/集合中不存在任何元素,则LINQ first()方法将抛出错误。

LINQ first()方法的语法

从列表中获取第一个元素的第一个方法的语法为:

int result = objList.First();

From the above syntax, we are getting the first element from the "objList" collection using the LINQ FIRST () method.

LINQ first()方法示例

下面是方法语法中的LINQ first()运算符的示例,用于从集合中获取第一个元素。

无涯教程网

C#代码

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 objList of the type of int
            int[] objList = { 1, 2, 3, 4, 5 };
//First() method is used to return the first element from the array 'objList'
            int result = objList.First();
            Console.WriteLine("Element from the List: {0}", result);
            Console.ReadLine();
        }
    }
}

From the above example, we are trying to get the first element from the collection of "objList" by using the LINQ FIRST () operator in method syntax.

输出:

方法语法中LINQ first()运算符的结果如下所示:

LINQ First() Element

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

下面是方法语法中的LINQ first()运算符的示例,用于从集合中获取第一个元素。

无涯教程网

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[] objList = { 1, 2, 3, 4, 5 };

            int result = (from l in objList select l).First();

            Console.WriteLine("Element from the List: {0}", result);

            Console.ReadLine();

        }

    }

    }

输出:

方法语法中LINQ first()运算符的结果如下所示:

LINQ First() Element




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

技术教程推荐

左耳听风 -〔陈皓〕

技术领导力实战笔记 -〔TGO鲲鹏会〕

算法面试通关40讲 -〔覃超〕

说透中台 -〔王健〕

NLP实战高手课 -〔王然〕

互联网人的英语私教课 -〔陈亦峰〕

基于人因的用户体验设计课 -〔刘石〕

朱涛 · Kotlin编程第一课 -〔朱涛〕

反爬虫兵法演绎20讲 -〔DS Hunter〕

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