LINQ 中的 Set 操作是指根据相同或不同集合(或集)中是否存在等效元素来生成结果集的查询操作。
下面一节中列出了执行 Set 操作的标准查询运算符方法。
方法
方法名 |
说明 |
C# 查询表达式语法 |
Visual Basic 查询表达式语法 |
更多信息 |
---|---|---|---|---|
Distinct |
从集合移除重复值。 |
不适用。 |
Distinct |
|
Except |
返回差集,差集是指位于一个集合但不位于另一个集合的元素。 |
不适用。 |
不适用。 |
|
Intersect |
返回交集,交集是指同时出现在两个集合中的元素。 |
不适用。 |
不适用。 |
|
Union |
返回并集,并集是指位于两个集合中任一集合的唯一的元素。 |
不适用。 |
不适用。 |
比较 Set 操作
Distinct
下图演示 Enumerable.Distinct 方法对字符序列的行为。返回的序列包含输入序列的唯一元素。
Except
下图演示 Enumerable.Except 的行为。返回的序列只包含位于第一个输入序列但不位于第二个输入序列的元素。
Intersect
下图演示 Enumerable.Intersect 的行为。返回的序列包含两个输入序列共有的元素。
Union
下图演示对两个字符序列执行的联合操作。返回的序列包含两个输入序列的唯一的元素。
查询表达式语法示例
下面的示例在 LINQ 查询中使用 Distinct 子句(仅在 Visual Basic 中可用)来返回整数列表中的唯一数字。
Dim classGrades = New System.Collections.Generic.List(Of Integer) From {63, 68, 71, 75, 68, 92, 75}
Dim distinctQuery = From grade In classGrades
Select grade Distinct
Dim sb As New System.Text.StringBuilder("The distinct grades are: ")
For Each number As Integer In distinctQuery
sb.Append(number & " ")
Next
' Display the results.
MsgBox(sb.ToString())
' This code produces the following output:
' The distinct grades are: 63 68 71 75 92