LINQ Set操作
集合操作
在四個操作符的集合操作中,每個產生基於不同的標準的結果。
操作
描述
C# 查詢表達式語法
VB查詢表達式語法
去重
結果:從集合唯一值的列表通過過濾重複的數據,如果有任何結果
不適用
不同的
除外
比較了兩個集合的值,並返回從一個集合不在另外一個集合
不適用
不適用
相交
返回集合在兩個不同的集合相同的相同部分
不適用
不適用
聯合
聯合了兩種不同內容的集合到一個列表太沒有任何重複的內容
不適用
不適用
DISTICT的例子 - 查詢表達式
VB
Module Module1 Sub Main() 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 MsgBox(sb.ToString()) End Sub End Module
當上述代碼被編譯和執行時,它產生了以下結果:
The distinct grades are: 63 68 71 75 92
Except例子 - Enumerable.Except方法
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Operators { class Program { static void Main(string[] args) { double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 }; double[] numbers2 = { 2.2 }; IEnumerable
VB
Module Module1 Sub Main() Dim numbers1() As Double = {2.0, 2.1, 2.2, 2.3, 2.4, 2.5} Dim numbers2() As Double = {2.2} Dim onlyInFirstSet As IEnumerable(Of Double) = numbers1.Except(numbers2) Dim output As New System.Text.StringBuilder For Each number As Double In onlyInFirstSet
output.AppendLine(number) Console.WriteLine(number) Next Console.ReadLine() End Sub End Module
當C#或VB的上述代碼被編譯和執行時,它產生了以下結果:
2
2.1
2.3
2.4
2.5
Intersect(相交)例子- Enumerable.Intersect方法
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Operators { class Program { static void Main(string[] args) { int[] id1 = { 44, 26, 92, 30, 71, 38 }; int[] id2 = { 39, 59, 83, 47, 26, 4, 30 }; IEnumerable
VB
Module Module1 Sub Main() Dim id1() As Integer = {44, 26, 92, 30, 71, 38} Dim id2() As Integer = {39, 59, 83, 47, 26, 4, 30} Dim intersection As IEnumerable(Of Integer) = id1.Intersect(id2) Dim output As New System.Text.StringBuilder For Each id As Integer In intersection
output.AppendLine(id) Console.WriteLine(id) Next Console.ReadLine() End Sub End Module
當C#或VB的上述代碼被編譯和執行時,它產生了以下結果:
26
30
Union例子- Enumerable.Union方法
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Operators { class Program { static void Main(string[] args) { int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 }; int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 }; IEnumerable
VB
Module Module1 Sub Main() Dim ints1() As Integer = {5, 3, 9, 7, 5, 9, 3, 7} Dim ints2() As Integer = {8, 3, 6, 4, 4, 9, 1, 0} Dim union As IEnumerable(Of Integer) = ints1.Union(ints2) Dim output As New System.Text.StringBuilder For Each num As Integer In union output.AppendLine(num & " ") Console.WriteLine(num & " ") Next Console.ReadLine() End Sub End Module
當C#或VB上述代碼被編譯和執行時,它產生了以下結果:
5
3
9
7
8
6
4
1
0