鮮明的存在2種口味,我知道的。第一個和默認的可以找到不同的原始類型。例如,如果你只想要獨特的名字,你可以運行這樣的items.Select(Function(x) x.Name).Distinct()
這樣的名字。要在多列上運行不同列表,您必須使用IEqualityComparer來協助它。
沒有一個可以使用的結構,我在這裏創建了一個名爲Item的類,用於匹配您的數據。以下是生成的代碼:
Public Class Item
Public Property Parent As String
Public Property Name As String
Public Property ID As String
End Class
該比較器可以是任何東西。我已經看到人們使用這個類本身,代碼運行的形式或者一個專門的類,就像我在這裏所做的那樣。
Public Class CompareThings
Implements IEqualityComparer(Of Item)
Public Overloads Function Equals(x As Item, y As Item) As Boolean Implements IEqualityComparer(Of Item).Equals
Return x.ID = y.ID AndAlso x.Name = y.Name
End Function
Public Overloads Function GetHashCode(obj As Item) As Integer Implements IEqualityComparer(Of Item).GetHashCode
Return (obj.Name & obj.ID).GetHashCode()
End Function
End Class
最後,要看到這個行動,你運行以下。
Dim things = New List(Of Item)(
{
New Item With {.Parent = "legacyparent1", .Name = "name1", .ID = "id1"},
New Item With {.Parent = "legacyparent1", .Name = "name2", .ID = "id2"},
New Item With {.Parent = "legacyparent1", .Name = "name2", .ID = "id2"},
New Item With {.Parent = "legacyparent1", .Name = "name1", .ID = "id1"},
New Item With {.Parent = "legacyparent1", .Name = "name1", .ID = "id1"}
})
Dim cmp As New CompareThings()
Dim results = things.Distinct(cmp)
For Each res In results
' Console.WriteLine($"ID: {res.ID}, Name: {res.Name}")
' In case you are running an older version of .NET that doesn't have the above feature
Console.WriteLine("ID: {0}, Name: {1}", res.ID, res.Name)
Next
這應該只給你兩個你想要的記錄。
我沒有提供連接,因爲在這種情況下,我試圖通過linq來修復結果,而不是修復sql查詢本身(如果我沿着這條路線走下去,我可能還需要額外打上數據庫)。通常情況下,我能夠剛剛得到我需要的第一次與SQL,但在這種情況下,我必須使用linq,我不是特別熟悉。 – gegillam