在LINQ中,first()方法/运算符用于根据指定的条件返回列表或集合中的项序列中的第一个元素或列表中项序列中的第一个元素。如果基于指定条件的列表/集合中不存在任何元素,则LINQ first()方法将抛出错误。
从列表中获取第一个元素的第一个方法的语法为:
int result = objList.First();
From the above syntax, we are getting the first element from the "objList" collection using the LINQ FIRST () method.
下面是方法语法中的LINQ first()运算符的示例,用于从集合中获取第一个元素。
C#代码
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 objList of the type of int int[] objList = { 1, 2, 3, 4, 5 }; //First() method is used to return the first element from the array 'objList' int result = objList.First(); Console.WriteLine("Element from the List: {0}", result); Console.ReadLine(); } } }
From the above example, we are trying to get the first element from the collection of "objList" by using the LINQ FIRST () operator in method syntax.
输出:
方法语法中LINQ first()运算符的结果如下所示:
下面是方法语法中的LINQ first()运算符的示例,用于从集合中获取第一个元素。
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) { int[] objList = { 1, 2, 3, 4, 5 }; int result = (from l in objList select l).First(); Console.WriteLine("Element from the List: {0}", result); Console.ReadLine(); } } }
输出:
方法语法中LINQ first()运算符的结果如下所示:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)