設定作業

LINQ 中的集合作業指的是讓查詢作業根據同一集合或不同集合內是否有對等項目來傳回結果集。

下節會列出執行集合作業的標準查詢運算子方法。

方法

方法名稱

描述

C# 查詢運算式語法

Visual Basic 查詢運算式語法

詳細資訊

Distinct

移除集合中的重複值。

不適用。

Distinct

Enumerable.Distinct

Queryable.Distinct

Except

傳回集合差異,表示出現在某個集合中,但沒有出現在另一個集合中的項目。

不適用。

不適用。

Enumerable.Except

Queryable.Except

Intersect

傳回集合交集,表示同時出現在兩個集合中的項目。

不適用。

不適用。

Enumerable.Intersect

Queryable.Intersect

Union

傳回集合聯集,表示將兩個集合集結後的項目 (去除重複項目)。

不適用。

不適用。

Enumerable.Union

Queryable.Union

集合作業的比較

Bb546153.collapse_all(zh-tw,VS.110).gifDistinct

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

顯示 Distinct() 之行為的圖形。

Bb546153.collapse_all(zh-tw,VS.110).gifExcept

下圖說明 Enumerable.Except 的行為。 傳回的序列只會包含出現在第一個輸入序列中,但沒出現在第二個輸入序列中的項目。

顯示 Except() 之動作的圖形。

Bb546153.collapse_all(zh-tw,VS.110).gifIntersect

下圖說明 Enumerable.Intersect 的行為。 傳回的序列會包含同時出現在這兩個輸入序列中的項目。

顯示兩種序列交集的圖形。

Bb546153.collapse_all(zh-tw,VS.110).gifUnion

下圖說明兩個字元序列的聯集作業。 傳回的序列包含兩個輸入序列集結後的項目 (去除重複項目)。

顯示兩個序列的聯集圖形。

查詢運算式語法範例

下列範例在 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 

請參閱

工作

HOW TO:合併和比較字串集合 (LINQ)

HOW TO:尋找兩個清單之間的差異 (LINQ)

參考

Distinct 子句 (Visual Basic)

System.Linq

概念

標準查詢運算子概觀