1

查看Select distinct by two properties in a list可以使用具有两个属性的 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)

正在工作,因此我猜我在这里缺少匿名类型中的相等性。

4

1 回答 1

1

你需要Key在属性之前写。喜欢

New With {Key element.Id, Key element.Name}在 VB 中。

所以,

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

有关详细信息,请参阅 VB 中匿名类型的文档。

于 2014-01-27T17:24:04.787 回答