本文概述
在LINQ中, Single()方法用于从集合中返回满足条件的单个元素。以防万一, 如果Single()方法在集合中找到多个元素或在集合中找不到任何元素, 则它将引发” InvalidOperationException”错误。
LINQ Single()方法的语法
使用LINQ Single()方法从集合中获取单个元素的语法。
int a = objList.Single();
在以上语法中, 我们使用LINQ 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<Student> objStudent = new List<Student>()
{
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”中获取单个元素。
输出