Distinct in LINQ with anonymous types (in VB.NET)

后端 未结 5 1447
醉梦人生
醉梦人生 2020-12-16 20:29

Supposing the referenced List below contains 2 elements:

Dim Countries = From c In List _
                Select New With { .Country = c.Country         


        
5条回答
  •  自闭症患者
    2020-12-16 21:02

    Distinct must know somehow which objects are the same. You select anonymus objects here, it doesn't know which are equal. I never wrote a single line of VB.Net, but I tried something, and it works:

    Module Module1
    
        Sub Main()
            Dim countries As List(Of Country) = New List(Of Country)
            Dim spain1 As Country = New Country()
            Dim spain2 As Country = New Country()
            Dim spain3 As Country = New Country()
            Dim hungary As Country = New Country()
            spain1.ID = 1
            spain1.Name = "Spain"
            spain2.ID = 1
            spain2.Name = "Spain"
            spain3.ID = 2
            spain3.Name = "Spain"
            hungary.ID = 3
            hungary.Name = "Hungary"
            countries.Add(spain1)
            countries.Add(spain2)
            countries.Add(spain3)
            countries.Add(hungary)
    
            Dim ctr = From c In countries Select c.Name, c.ID
                      Distinct
    
            For Each c In ctr
                Console.WriteLine(c)
            Next
        End Sub
    
        Public Class Country
    
            Protected _name As String
    
            Protected _id As Long
    
            Public Property Name() As String
                Get
                    Return _name
                End Get
                Set(ByVal value As String)
                    _name = value
                End Set
            End Property
    
            Public Property ID() As Long
                Get
                    Return _id
                End Get
                Set(ByVal value As Long)
                    _id = value
                End Set
            End Property
    
        End Class
    End Module
    

    In your case:

    Dim Countries = From c In List 
                    Select c.Country, c.CountryID Distinct
    

提交回复
热议问题