ASP.NET List<T> 集合運算 聯集、交集、差集
集合運算和集合關係
ASPX 集合運算、集合代數中包含的稱為元素,而由元素所組成的又稱 Union, Intersection Operation 集合運算。
Union 聯集 A 集合和 B 集合間的聯集 A ∪ B,所有包含在 A 或 B 的元素所組成的集合。
Relational Algebra, Gather, Assemble, Collect 運算並集、交集、補集、差集等集合。
Intersection 交集 A 集合和 B 集合間的交集 A ∩ B,所有同時重複包含在 A 和 B 的元素所組成的集合。
Difference 差集 B 集合在 A 集合中的差集,是由所有屬於 A 集合但不屬於 B 集合的元素所組成的集合。
Dim Part_A_Tables() As String = {"固定座", "皮帶輪", "傳動軸"}
Dim Part_B_Tables() As String = {"皮帶輪", "濾清器", "傳動軸"}
Dim Part_Charts As New List(Of String)(Part_A_Tables)
Part_Charts.AddRange(Part_B_Tables) '合併陣列
固定座, 皮帶輪, 傳動軸, 皮帶輪, 濾清器, 傳動軸
Union 聯集(且去除重複的值)
Dim Part_Union As New List(Of String)
For Each Item As String In Part_Charts
If Not Part_Union.Contains(Item) Then
Part_Union.Add(Item)
End If
Next Item
固定座, 皮帶輪, 傳動軸, 濾清器
同樣的結果、使用 System.Linq.Enumerable 方法,在列舉查詢「聯集」的集合。
Dim Enum_Union As IEnumerable = Part_A_Tables.Union(Part_B_Tables)
For Each Item As String In Enum_Union
Response.Write( Item & ", ")
Next Item
固定座, 皮帶輪, 傳動軸, 濾清器
Intersection 交集
Dim Part_Intersection As New List(Of String)
For Each ItemA As String In Part_A_Tables
For Each ItemB As String In Part_B_Tables
If (ItemA = ItemB) And (Not Part_Intersection.Contains(ItemA)) Then
Part_Intersection.Add(ItemA)
End If
Next ItemB
Next ItemA
皮帶輪, 傳動軸
同樣的結果、使用 System.Linq.Enumerable 方法,在列舉查詢「交集」的集合。
Dim Enum_Intersection As IEnumerable = Part_A_Tables.Intersect(Part_B_Tables)
皮帶輪, 傳動軸
Difference 差集
Dim Part_Difference As New List(Of String)(Part_A_Tables)
For Each Item As String In Part_B_Tables
If Part_Difference.Contains(Item) Then
Part_Difference.Remove(Item)
End If
Next Item
固定座
使用 Except 產生兩個集合的差異定義為第一個集合的成員,該集合不會出現在第二個集合中。
Dim Enum_Difference1 As IEnumerable = Part_A_Tables.Except(Part_B_Tables)
固定座
反向 Difference 差集
Dim Part_Difference As New List(Of String)(Part_B_Tables)
For Each Item As String In Part_A_Tables
If Part_Difference.Contains(Item) Then
Part_Difference.Remove(Item)
End If
Next Item
濾清器
Dim Enum_Difference2 As IEnumerable = Part_B_Tables.Except(Part_A_Tables)
濾清器
聯集 Union 去除重複的數值
使用 System.Linq.Enumerable 方法的 Distinct() 來比較 List<T> 值,去除重複的數值。
Dim NumberUnion As New List(Of Int16)({100, 200, 500, 100, 200, 500, 50 })
Dim distinctUnion As IEnumerable = NumberUnion.Distinct()
For Each Item As Int16 In distinctUnion
Response.Write ( Item & ", " )
Next Item
100, 200, 500, 50