DistinctBy与VB.NET中的两个属性

时间:2014-01-27 17:13:19

标签: vb.net morelinq

查看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)

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

1 个答案:

答案 0 :(得分:1)

您需要在属性之前写Key。像

VB中的

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

所以,

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

有关详细信息,请参阅VB中anonymous types的文档。