DistinctBy with two properties in VB.NET

2019-03-02 15:36发布

问题:

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.