看着选择列表中两个不同的属性可以使用具有两个属性的 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)
正在工作,因此我猜测我在这里缺少匿名类型中的相等性。
你需要写Key
在财产之前。喜欢
New With {Key element.Id, Key element.Name}
in VB.
So,
Result = TestList.DistinctBy(Function(element) New With {Key element.Id, Key element.Name})
请参阅文档匿名类型在 VB 中了解更多详细信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)