LINQ 中的集运算是指根据相同或不同集合(或集)中是否存在等效元素来生成结果集的查询运算。
以下部分列出了执行集作的标准查询运算符方法。
方法
方法名 | DESCRIPTION | Visual Basic 查询表达式语法 | 详细信息 |
---|---|---|---|
Distinct 或 DistinctBy | 删除集合中的重复值。 | Distinct |
Enumerable.Distinct Enumerable.DistinctBy Queryable.Distinct Queryable.DistinctBy |
Except 或 ExceptBy | 返回集合差异,即一个集合中不在第二个集合中出现的元素。 | 不適用。 | Enumerable.Except Enumerable.ExceptBy Queryable.Except Queryable.ExceptBy |
Intersect 或 IntersectBy | 返回交集,交集指同时出现在两个集合中的元素。 | 不適用。 | Enumerable.Intersect Enumerable.IntersectBy Queryable.Intersect Queryable.IntersectBy |
Union 或 UnionBy | 返回并集,并集指位于两个集合中任一集合的唯一的元素。 | 不適用。 | Enumerable.Union Enumerable.UnionBy Queryable.Union Queryable.UnionBy |
集合运算的比较
不同
如下图所示,Enumerable.Distinct 方法对字符序列的行为进行了描述。 返回的序列包含输入序列的唯一元素。
除了
下图描绘了 Enumerable.Except 的行为。 返回的序列仅包含第一个输入序列中不在第二个输入序列中的元素。
相交
下图描绘了 Enumerable.Intersect 的行为。 返回的序列包含两个输入序列共有的元素。
联盟
下图描绘了对两个字符序列的联合操作。 返回的序列包含两个输入序列的唯一元素。
查询表达式语法示例
以下示例使用 Distinct
LINQ 查询中的子句从整数列表中返回唯一的数字。
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