📅  最后修改于: 2021-01-06 05:33:28             🧑  作者: Mango
在LINQ中,Single()方法用于从集合中返回满足条件的单个元素。如果Single()方法在集合中找到多个元素或在集合中找不到任何元素,则它将引发“ InvalidOperationException ”错误。
使用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.
List objStudent = 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; }
}
}
在上面的示例中,我们使用LINQ Single()运算符从集合“ objStudent”中获取单个元素。
输出: