In LINQ, the Single() method is used to return the single element from the collection, which satisfies the condition. In case, if the Single() method found more than one element in collection or no element in the collection, then it will throw the "InvalidOperationException" error.
使用LINQ Single()方法从集合中获取单个元素的语法。
int a = objList.Single();
在上面的语法中,我们使用LINQ Single()方法从列表中获取单个元素。
以下是LINQ Single()方法从集合中获取单个元素的示例。
using System; using System. Collections; using System.Collections.Generic; using System. Linq; using System. Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Programme2 { static void Main(string[] args) { //create an object objStudent of the class Student added the record to the list. ListobjStudent = new List () { new Student() { Name = "Shubham Rastogi", Gender = "Male",Location="Chennai" }, new Student() { Name = "Rohini Tyagi", Gender = "Female", Location="Chennai" }, new Student() { Name = "Praveen Alavala", Gender = "Male",Location="Bangalore" }, new Student() { Name = "Sateesh Rastogi", Gender = "Male", Location ="Vizag"}, new Student() { Name = "Madhav Sai", Gender = "Male", Location="Nagpur"} }; //initialize the array objList int[] objList = { 1 }; //objStudent.Single() used to select the student var user = objStudent.Single(s => s.Name == "Shubham Rastogi"); string result = user.Name; int val = objList.Single(); Console.WriteLine("Element from objStudent: {0}", result); Console.WriteLine("Element from objList: {0}", val); Console.ReadLine(); } } class Student { public string Name { get; set; } public string Gender { get; set; } public string Location { get; set; } } }
From the above example, we are getting the single element from the collection "objStudent" using the LINQ Single() operator.
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)