在 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 ElementAtOrDefault()用法及代碼示例
- LINQ AsEnumrable()用法及代碼示例
- LINQ ToLookup()用法及代碼示例
- LINQ Count()用法及代碼示例
- LINQ Single()用法及代碼示例
- LINQ sum()用法及代碼示例
- LINQ ToArray()用法及代碼示例
- LINQ Min()用法及代碼示例
- LINQ ToDictionary()用法及代碼示例
- LINQ LastOrDefault()用法及代碼示例
- LINQ FirstOrDefault()用法及代碼示例
- LINQ GroupBy()用法及代碼示例
- LINQ Cast()用法及代碼示例
- LINQ ToList()用法及代碼示例
- LINQ Max()用法及代碼示例
- LINQ Aggregate()用法及代碼示例
- LINQ DefaultfEmpty()用法及代碼示例
- LINQ Last()用法及代碼示例
- LINQ OfType()用法及代碼示例
- Lodash _.sampleSize()用法及代碼示例
注:本文由純淨天空篩選整理自 LINQ ElementAt() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。