在LINQ中,ElementAtOrDefault()方法用于获取列表/集合中指定索引位置的元素,与LINQElementAt()方法相同。ElementAtOrDefault()和ElementAt()之间的唯一区别是它只返回默认值。另一方面,如果列表中不存在元素的指定索引位置,那么在这种情况下,这也将返回默认值。
使用LINQ ElementAtOrDefault()获取指定索引位置的元素的语法。
int result = objList.ElementAtOrDefault(1);
根据上述语法,我们将获取指定索引位置的元素。
下面是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.
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)