DistinctBy with two properties in VB.NET

陌路散爱 提交于 2019-12-02 06:55:59

问题


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

Test Class:

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

Test Method:

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

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.


回答1:


You need to write Key before property. like

New With {Key element.Id, Key element.Name} in VB.

So,

Result = TestList.DistinctBy(Function(element) New With {Key element.Id, Key element.Name})

See the documentation for anonymous types in VB for more details.



来源:https://stackoverflow.com/questions/21387209/distinctby-with-two-properties-in-vb-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!