在VB.NET中具有两个属性 [英] DistinctBy with two properties in VB.NET
问题描述
查看在一个列表,可以使用具有两个属性的DistinctBy扩展方法.我试图将其转换为vb.net,但没有得到预期的结果
Looking at Select distinct by two properties in a list it is possible to use the DistinctBy extensionmethod with two properties. I tried to convert this to vb.net, but I'm not getting the expected results
测试类:
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中使用匿名类型完全可以吗? 做这样的事情:
Is this at all possible in vb.net using anonymous types? Doing something like this:
Result = TestList.DistinctBy(Function(element) element.Id & "-" & element.Name)
在工作,因此我猜我在这里缺少了匿名类型相等的东西.
is working, therefore I'm guessing I'm missing something with equality in anonymous types here.
推荐答案
您需要在属性之前写入Key
.喜欢
You need to write Key
before property. like
New With {Key element.Id, Key element.Name}
.
所以
Result = TestList.DistinctBy(Function(element) New With {Key element.Id, Key element.Name})
有关更多详细信息,请参见VB中匿名类型的文档.
See the documentation for anonymous types in VB for more details.
这篇关于在VB.NET中具有两个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!