Set 运算

LINQ 中的 Set 操作是指根据相同或不同集合(或集)中是否存在等效元素来生成结果集的查询操作。

下面一节中列出了执行 Set 操作的标准查询运算符方法。

方法

方法名

说明

C# 查询表达式语法

Visual Basic 查询表达式语法

更多信息

Distinct

从集合移除重复值。

不适用。

Distinct

Enumerable.Distinct

Queryable.Distinct

Except

返回差集,差集是指位于一个集合但不位于另一个集合的元素。

不适用。

不适用。

Enumerable.Except

Queryable.Except

Intersect

返回交集,交集是指同时出现在两个集合中的元素。

不适用。

不适用。

Enumerable.Intersect

Queryable.Intersect

Union

返回并集,并集是指位于两个集合中任一集合的唯一的元素。

不适用。

不适用。

Enumerable.Union

Queryable.Union

比较 Set 操作

Distinct

下图演示 Enumerable.Distinct 方法对字符序列的行为。 返回的序列包含输入序列的唯一元素。

显示 Distinct() 的行为的图。

Except

下图演示 Enumerable.Except 的行为。 返回的序列只包含位于第一个输入序列但不位于第二个输入序列的元素。

显示 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 

请参见

任务

如何:组合和比较字符串集合 (LINQ)

如何:查找两个列表之间的差集 (LINQ)

参考

Distinct 子句 (Visual Basic)

System.Linq

概念

标准查询运算符概述