Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在VB.NET中使用两个属性进行区分_Vb.net_Morelinq - Fatal编程技术网

在VB.NET中使用两个属性进行区分

在VB.NET中使用两个属性进行区分,vb.net,morelinq,Vb.net,Morelinq,现在来看,可以使用带有两个属性的DistinctBy extensionmethod。我试图将其转换为vb.net,但没有得到预期的结果 测试等级: Public Class Test Public Property Id As Integer Public Property Name As String Public Overrides Function ToString() As String Return Id & " - " &

现在来看,可以使用带有两个属性的DistinctBy extensionmethod。我试图将其转换为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)
是有效的,所以我猜我在匿名类型中缺少了一些相等的东西

您需要在属性之前写入密钥。像

在VB中使用{Key element.Id,Key element.Name}新建

所以


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

您收到的错误消息是什么?你的代码应该可以正常工作。您需要在属性之前添加键来比较两个匿名类型实例是否相等。有关更多详细信息,请参阅VB中的匿名类型文档@MarcinJuraszek。代码运行正常,是的。但是最后一个结果与我所寻找的不同,这两个输出都在上面的代码中。使用关键字现在工作得很好!
Result = TestList.DistinctBy(Function(element) New With {Key element.Id, Key element.Name})