設定作業
LINQ 中的集合作業指的是讓查詢作業根據同一集合或不同集合內是否有對等項目來傳回結果集。
下節會列出執行集合作業的標準查詢運算子方法。
方法
方法名稱 |
描述 |
C# 查詢運算式語法 |
Visual Basic 查詢運算式語法 |
詳細資訊 |
---|---|---|---|---|
Distinct |
移除集合中的重複值。 |
不適用。 |
Distinct |
|
Except |
傳回集合差異,表示出現在某個集合中,但沒有出現在另一個集合中的項目。 |
不適用。 |
不適用。 |
|
Intersect |
傳回集合交集,表示同時出現在兩個集合中的項目。 |
不適用。 |
不適用。 |
|
Union |
傳回集合聯集,表示將兩個集合集結後的項目 (去除重複項目)。 |
不適用。 |
不適用。 |
集合作業的比較
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