VB.NET 无法返回基于唯一值的列表

问题描述 投票:0回答:1

使用 VB.NET,我收到一个对象列表。我需要从这个对象列表中清除重复的数据集,以便该列表基于所有列都是唯一的。在 StackOverflow 上阅读,总体思路是使用

GroupBy
后跟
Select
,但是每当我尝试这样做时,整个集合仍然会返回。

对于这个给定的示例,我预计 uniqueData 中的计数为 3,但它仍然为 4。dataSet1 和 dataSet2 应该被视为彼此的重复

Module Program
    Sub Main(args As String())
        Dim data As New PersonCollection With {.PersonCollection = New List(Of PersonInfo)}
        Dim dataSet1 As New PersonInfo With {.FirstName = "Bob", .LastName = "Smith", .Rating = 10}
        Dim dataSet2 As New PersonInfo With {.FirstName = "John", .LastName = "Hurt", .Rating = 20}
        Dim dataSet3 As New PersonInfo With {.FirstName = "Bob", .LastName = "Smith", .Rating = 30}
        Dim dataSet4 As New PersonInfo With {.FirstName = "Bob", .LastName = "Smith", .Rating = 10}
        data.PersonCollection.Add(dataSet1)
        data.PersonCollection.Add(dataSet2)
        data.PersonCollection.Add(dataSet3)
        data.PersonCollection.Add(dataSet4)

        Dim uniqueData = data.PersonCollection.GroupBy(Function(x) New With {x.FirstName, x.LastName, x.Rating}).Select(Function(x) x.First).ToList()

        Console.ReadLine()
    End Sub


    Private Class PersonCollection
        Property PersonCollection As List(Of PersonInfo)
    End Class

    Private Class PersonInfo
        Property FirstName As String
        Property LastName As String
        Property Rating As Integer
    End Class
End Module
vb.net
1个回答
0
投票

尝试使用 tuple 来代替,因为它具有值语义,而不是具有引用语义的匿名类类型。

.GroupBy((x.FirstName, x.LastName, x.Rating))

请注意,语法

New With {x.FirstName ...
确实适用于 O/R 映射器,因为随后它会被转换为 SQL,并且值和引用语义之间的区别不再适用。

© www.soinside.com 2019 - 2024. All rights reserved.