在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" 中獲取單個元素。
輸出:

相關用法
- LINQ AsEnumrable()用法及代碼示例
- LINQ ToLookup()用法及代碼示例
- LINQ ElementAtOrDefault()用法及代碼示例
- LINQ Count()用法及代碼示例
- LINQ sum()用法及代碼示例
- LINQ ToArray()用法及代碼示例
- LINQ Min()用法及代碼示例
- LINQ ToDictionary()用法及代碼示例
- LINQ LastOrDefault()用法及代碼示例
- LINQ FirstOrDefault()用法及代碼示例
- LINQ GroupBy()用法及代碼示例
- LINQ Cast()用法及代碼示例
- LINQ ToList()用法及代碼示例
- LINQ Max()用法及代碼示例
- LINQ Aggregate()用法及代碼示例
- LINQ DefaultfEmpty()用法及代碼示例
- LINQ Last()用法及代碼示例
- LINQ ElementAt()用法及代碼示例
- LINQ OfType()用法及代碼示例
- Lodash _.sampleSize()用法及代碼示例
注:本文由純淨天空篩選整理自 LINQ Single() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。