元素运算符用于从序列或集合中返回单个或特定元素。例如,当我们问学校时,校长是谁?这样一来,只有一人成为学校的校长。因此,学生人数是一个集合,而校长是唯一来自集合的结果。
LINQ标准查询运算符支持8种类型的元素运算符:
- ElementAt
- ElementAtOrDefault
- 第一的
- 第一或默认
- 最后的
- LastOrDefault
- 单身的
- 单一或默认
单一运营商
单个运算符用于返回集合或序列的单个元素。或返回指定给定条件的单个元素。可以通过两种不同的方式重载此方法:
- 单个
(IEnumerable 此方法返回集合或序列中唯一指定给定条件的元素,如果存在多个指定给定条件的元素,则将引发异常。,Func ): - Single
(IEnumerable 此方法返回给定序列或集合中的唯一元素,如果序列或集合中不存在一个完全相同的元素,则引发异常。):
重要事项:
- 它不支持C#和VB.Net语言的查询语法。
- 它支持C#和VB.Net语言的方法语法。
- 它同时存在于Queryable和Enumerable类中。
- 如果序列不包含指定给定条件的元素,或者序列包含多个指定给定条件的元素,或者序列为空,则抛出InvalidOperationException 。
范例1:
// C# program to illustrate the
// use of Single operator
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
static public void Main()
{
// Data source
int[] sequence1 = {112, 44, 55, 66, 77, 777, 56};
int[] sequence2 = {2};
// Get the element which specifies the given
// condition Using Single(Condition) function
var result1 = sequence1.Single(seq => seq == 112);
Console.WriteLine("Element: {0}", result1);
// Get the only element of the
// sequence Using Single() function
var result2 = sequence2.Single();
Console.WriteLine("Element: {0}", result2);
// This commented part gives you exception
// because the given sequence does not
// contain elements
/*
int[] sequence3 = {};
var result3 = sequence3.Single();
Console.WriteLine("Element: {0}", result3);
*/
}
}
输出:
Element: 112
Element: 2
范例2:
// C# program to find the
// name of the employee
using System;
using System.Linq;
using System.Collections.Generic;
// Employee details
public class Employee {
public int emp_id
{
get;
set;
}
public string emp_name
{
get;
set;
}
public string emp_gender
{
get;
set;
}
public string emp_hire_date
{
get;
set;
}
public int emp_salary
{
get;
set;
}
}
class GFG {
// Main method
static public void Main()
{
List emp = new List() {
new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female",
emp_hire_date = "12/3/2017", emp_salary = 20000},
new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female",
emp_hire_date = "22/4/2018", emp_salary = 30000},
new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male",
emp_hire_date = "3/5/2016", emp_salary = 40000},
new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female",
emp_hire_date = "4/8/2017", emp_salary = 40000},
new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male",
emp_hire_date = "12/1/2016", emp_salary = 40000},
new Employee() {emp_id = 214, emp_name = "Anupriya", emp_gender = "Female",
emp_hire_date = "17/6/2015", emp_salary = 50000},
};
// Query to find the name the
// employee Using Single method
var res = emp.Single(e => e.emp_name == "Anjita");
string val = res.emp_name;
Console.WriteLine("Employee name: {0}", val);
}
}
输出:
Employee name: Anjita