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

LINQ ElementAtOrDefault()方法

本文概述

在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 ElementAtOrDefault()方法

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

评论 抢沙发

评论前必须登录!