當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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() Method



相關用法


注:本文由純淨天空篩選整理自 LINQ ElementAt() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。