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

LINQ ElementAt()方法

本文概述

在LINQ中, ElementAt()运算符用于根据指定的索引从列表/集合中返回元素。

通常, 在列表中, 索引将从零开始, 因此, 如果要获取第一个元素, 则需要发送零(0)作为索引位置。

LINQ ElementAt()方法的语法

int result = objList.ElementAt(1);

在上面的语法中, 我们将元素从集合中的第二个索引位置元素处获取。

LINQ ElementAt()方法的示例

这是使用LINQ ElementAt()方法在指定索引位置获取元素的示例。

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 named 'a' type int with assigning values
            int[] a = { 1, 2, 3, 4, 5 };
/*With the help of ElementAt() method will fetch the element from
    the specified position and store the value in 'result' and 'val' variable.*/
            int result = a.ElementAt(1);
            int val = a.ElementAt(3);
/*WriteLine function will print the value of the specified index*/
            Console.WriteLine("Element At Index 1: {0}", result);
            Console.WriteLine("Element At Index 3: {0}", val);
            Console.ReadLine();
        }

    }

    }

从上面的示例中, 我们试图基于不同的索引位置获取集合中的不同元素。

输出

LINQ ElementAt()方法

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

评论 抢沙发

评论前必须登录!