設定作業 (Visual Basic)

LINQ 中的設定作業指的是產生結果集的查詢作業,而結果集是根據相同或不同集合 (集) 內是否有對等項目而定。

下節列出執行設定作業的標準查詢運算子方法。

方法

方法名稱 描述 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

比較設定作業

Distinct

下圖說明一連串字元的 Enumerable.Distinct 方法行為。 所傳回的序列包含輸入序列中的唯一項目。

Graphic showing the behavior of Distinct().

Except

下圖說明 Enumerable.Except 的行為。 所傳回的序列只包含第一個輸入序列中不在第二個輸入序列中的項目。

Graphic showing the action of Except().

Intersect

下圖說明 Enumerable.Intersect 的行為。 所傳回的序列包含兩個輸入序列共有的項目。

Graphic showing the intersection of two sequences.

Union

下圖說明兩個字元序列的聯合作業。 所傳回的序列包含兩個輸入序列中的唯一項目。

Graphic showing the union of two sequences.

查詢運算式語法範例

下列範例在 LINQ 查詢中使用 Distinct 子句,以從整數清單中傳回唯一的數字。


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 

另請參閱