ElementAtOrDefault运算符

ElementAtOrDefault运算符 首页 / LinQ入门教程 / ElementAtOrDefault运算符

在LINQ中,ElementAtOrDefault()方法用于获取列表/集合中指定索引位置的元素,与LINQElementAt()方法相同。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();
        }
    }
}

From the above example, we are getting the different elements from the list based on the specified index. Here we specified the position of the index "10," which does not exist in the list; in this case, this will return the default value.

输出:

LINQ ElementAtOrDefault() Method




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

技术教程推荐

从0开始学微服务 -〔胡忠想〕

TensorFlow快速入门与实战 -〔彭靖田〕

Service Mesh实战 -〔马若飞〕

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

代码之丑 -〔郑晔〕

郭东白的架构课 -〔郭东白〕

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

给程序员的写作课 -〔高磊〕

云原生基础架构实战课 -〔潘野〕

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