C#-LINQ中的ElementAt()操作符来返回基于索引号的元素

221 阅读2分钟

语言集成查询语言(LINQ)被用来对C#集合或普通数据结构进行操作。我们也可以用LINQ执行数据库查询操作。LINQ支持许多用于数据操作的方法和函数,如更新、删除和插入等。

LINQ ElementAt****操作符

LINQ ElementAt()操作符被用来搜索数据源中的元素。它根据提供的索引值来搜索元素。

语法

input\_source.ElementAt(index\_number);

其中input_source是数据源,可以是一个数组或列表或任何集合。

我们将通过下面的例子进一步理解这一点。

正如我们所知,索引从0开始。

例子1

在这里,我们将创建一个有10个整数的列表,并根据ElementAt()中提供的索引号来获取元素。

using System;
using System.Linq;
using System.Collections.Generic;

 //create a class - Linuxhint
class Linuxhint
{
 
    static public  void Main(){
       
       //create List named input_numbers
       var input_numbers = new  List() {100,200,300,456,12,34,56,78,54,44};
     
       //return 6th value  
        Console.WriteLine("Element present at 6th position: "+input_numbers.ElementAt(5));
       
        //return 9th value  
        Console.WriteLine("Element present at 9th position: "+input_numbers.ElementAt(8));
       
        //return 1st value  
        Console.WriteLine("Element present at 1st position: "+input_numbers.ElementAt(0));
       
        //return 4th value  
        Console.WriteLine("Element present at 4th position: "+input_numbers.ElementAt(3));
       
        //return 10th value  
        Console.WriteLine("Element present at 10th position: "+input_numbers.ElementAt(9));
       
    }
           
}

输出

解释
1
.首先,我们创建了一个名为input_numbers的列表,里面有10个整数元素:

2.之后,我们使用它们的索引位置搜索并显示下列数值:

例2

在这里,我们将创建一个有3个字符串的列表,并根据ElementAt()里面提供的索引号来获取元素。

using System;
using System.Linq;
using System.Collections.Generic;

 //create a class - Linuxhint
class Linuxhint
{
 
    static public  void Main(){
       
       //create List named input_strings
       var input_strings = new  List() {"Linuxhint","c#","vignan"};
     
       //return 1st value  
        Console.WriteLine("Element present at 1st  position: "+input_strings.ElementAt(0));
       
        //return 3rd value  
        Console.WriteLine("Element present at 3rd position: "+input_strings.ElementAt(2));
       
       
    }
           
}

输出

解释
1
.首先,我们创建了一个名为input_strings的列表,里面有3个字符串元素:

2.之后,我们使用它们的索引位置搜索并显示以下字符串:

结论

我们学习了如何使用C#-LINQ中的ElementAt()操作符来返回基于索引号的元素。我们演示了两个不同的例子来更好地理解这个概念,并确保在你的代码中使用这些模块--使用System,使用System.Linq,使用System.Collections.Generic