1
看着Select distinct by two properties in a list有可能使用帶有兩個屬性的DistinctBy擴展方法。我試圖將其轉換爲vb.net,但我沒有得到預期的結果DistinctBy在VB.NET中有兩個屬性
測試類:
Public Class Test
Public Property Id As Integer
Public Property Name As String
Public Overrides Function ToString() As String
Return Id & " - " & Name
End Function
End Class
測試方法:
Private Sub RunTest()
Dim TestList As New List(Of Test)
TestList.Add(New Test() With {.Id = 1, .Name = "A"})
TestList.Add(New Test() With {.Id = 2, .Name = "A"})
TestList.Add(New Test() With {.Id = 3, .Name = "A"})
TestList.Add(New Test() With {.Id = 1, .Name = "A"})
TestList.Add(New Test() With {.Id = 1, .Name = "B"})
TestList.Add(New Test() With {.Id = 1, .Name = "A"})
Dim Result As IEnumerable(Of Test)
Result = TestList.DistinctBy(Function(element) element.Id)
'1 - A
'2 - A
'3 - A
Result = TestList.DistinctBy(Function(element) element.Name)
'1 - A
'1 - B
Result = TestList.DistinctBy(Function(element) New With {element.Id, element.Name})
'1 - A
'2 - A
'3 - A
'1 - A
'1 - B
'1 - A
'Expected:
'1 - A
'2 - A
'3 - A
'1 - B
End Sub
這是在VB在所有可能的.net使用匿名類型? 做這樣的事情:
Result = TestList.DistinctBy(Function(element) element.Id & "-" & element.Name)
工作,所以我猜我錯過了與匿名類型這裏平等的東西。
你得到的錯誤信息是什麼?你的代碼應該工作得很好。 – MarcinJuraszek
是的。您需要在屬性之前添加Key以比較兩個匿名類型實例的相等性。 –
有關詳細信息,請參閱VB中匿名類型的文檔,網址爲http://msdn.microsoft.com/en-us/library/bb384767.aspx –