除了DefaultIfEmpty,其余八种标准查询元素运算符从集合返回单个元素。
操作 | 描述 | C#查询表达式语法 | VB查询表达式语法 |
---|---|---|---|
ElementAt | 返回一个特定的索引中的一个元素存在于一个集合 | 不适用 | 不适用 |
ElementAtOrDefault | 相同于ElementAt,它也将返回默认值,特定索引超出范围返回默认值 | 不适用 | 不适用 |
First | 检索的集合或第一元件满足特定的条件中的第一个元素 | 不适用 | 不适用 |
FirstOrDefault | 相同First除了返回一个默认值没有存在这样的元素 | 不适用 | 不适用 |
Last | 检索最后一个出现在集合或最后一个元素的元素满足特定条件 | 不适用 | 不适用 |
LastOrDefault | 相同Last除了返回一个默认值没有存在任何这样的元素 | 不适用 | 不适用 |
Single | 返回集合的唯一元素或唯一元素满足一定条件 | 不适用 | 不适用 |
SingleOrDefault | 相同单除了它也返回一个默认值,如果没有存在任何这样的唯一元素 | 不适用 | 不适用 |
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