LINQ 中的元素运算符
除了 DefaultIfEmpty 之外,其余八个标准查询元素运算符都从集合中返回单个元素。
| 运算符 | 描述 | C# 查询表达式语法 | VB 查询表达式语法 |
|---|---|---|---|
| ElementAt | 返回集合中特定索引处的元素 | 不适用 | 不适用 |
| ElementAtOrDefault | 与 ElementAt 相同,不同之处在于如果特定索引超出范围,它还会返回默认值 | 不适用 | 不适用 |
| First | 检索集合中的第一个元素或满足特定条件的第一个元素 | 不适用 | 不适用 |
| FirstOrDefault | 与 First 相同,不同之处在于如果不存在此类元素,它还会返回默认值 | 不适用 | 不适用 |
| Last | 检索集合中存在的最后一个元素或满足特定条件的最后一个元素 | 不适用 | 不适用 |
| LastOrDefault | 与 Last 相同,不同之处在于如果不存在任何此类元素,它还会返回默认值 | 不适用 | 不适用 |
| Single | 返回集合中的唯一元素或满足特定条件的唯一元素 | 不适用 | 不适用 |
| SingleOrDefault | 与 Single 相同,不同之处在于如果不存在任何此类唯一元素,它还会返回默认值 | 不适用 | 不适用 |
| DefaultIfEmpty | 如果集合或列表为空或为 null,则返回默认值 | 不适用 | 不适用 |
ElementAt - Enumerable.ElementAt 方法示例
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Operators {
class Program {
static void Main(string[] args) {
string[] names = { "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };
Random random = new Random(DateTime.Now.Millisecond);
string name = names.ElementAt(random.Next(0, names.Length));
Console.WriteLine("The name chosen at random is '{0}'.", name);
Console.ReadLine();
}
}
}
VB
Module Module1
Sub Main()
Dim names() As String = _{"Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu"}
Dim random As Random = New Random(DateTime.Now.Millisecond)
Dim name As String = names.ElementAt(random.Next(0, names.Length))
MsgBox("The name chosen at random is " & name)
End Sub
End Module
当编译并执行上述 C# 或 VB 代码时,它会产生以下结果:
The name chosen at random is Ito, Shu
注意 - 此处,上述输出将动态变化,并且名称将随机选择。
First - Enumerable.First 方法示例
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Operators {
class Program {
static void Main(string[] args) {
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19 };
int first = numbers.First();
Console.WriteLine(first);
Console.ReadLine();
}
}
}
VB
Module Module1
Sub Main()
Dim numbers() As Integer = _{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19}
Dim first As Integer = numbers.First()
MsgBox(first)
End Sub
End Module
当编译并执行上述 C# 或 VB 代码时,它会产生以下结果:
9
Last - Enumerable.Last 方法示例
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Operators {
class Program {
static void Main(string[] args) {
int[] numbers = { 9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19 };
int last = numbers.Last();
Console.WriteLine(last);
Console.ReadLine();
}
}
}
VB
Module Module1
Sub Main()
Dim numbers() As Integer = _{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19};
Dim last As Integer = numbers.Last()
MsgBox(last)
End Sub
End Module
当编译并执行上述 C# 或 VB 代码时,它会产生以下结果:
19
linq_query_operators.htm
广告