在 LINQ 中,ElementAtOrDefault() 方法用於獲取列表/集合中指定索引位置的元素,與 LINQ ElementAt() 方法相同。 ElementAtOrDefault() 和 ElementAt() 的唯一區別是它隻會返回默認值。另一方麵,如果元素的指定索引位置在列表中不存在,那麽在這種情況下,這也將返回默認值。
LINQ ElementAtOrDefault() 方法的語法
使用 LINQ ElementAtOrDefault() 獲取指定索引位置元素的語法。
int result = objList.ElementAtOrDefault(1);
從上麵的語法中,我們正在獲取指定索引位置的元素。
LINQ ElementAtOrDefault() 方法示例
以下是獲取指定索引位置元素的 LINQ ElementAtOrDefault() 方法示例。
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 'a' type of int having the values at specified 5 index
int[] a = { 1, 2, 3, 4, 5,6 };
//ElementAtOrDefault() method will return the value from the specified index
int result = a.ElementAtOrDefault(1);
int val = a.ElementAtOrDefault(3);
/*here ElementAtOrDefault() method will return the default value '0'
because the array 'a' does not contain any value at index 10 position*/
int val1 = a.ElementAtOrDefault(10);
Console.WriteLine("Element At Index 1:{0}", result);
Console.WriteLine("Element At Index 3:{0}", val);
Console.WriteLine("Element At Index 10:{0}", val1);
Console.ReadLine();
}
}
}
從上麵的例子中,我們根據指定的索引從列表中獲取不同的元素。這裏我們指定了列表中不存在的索引"10,"的位置;在這種情況下,這將返回默認值。
輸出:

相關用法
- LINQ ElementAt()用法及代碼示例
- 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 ElementAtOrDefault() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。