Sorting a list of <Object> with VB and LINQ

2020-07-06 03:22发布

问题:

I'm trying out some LINQ expressions and can't get them to work with the List class. Basically I want to be able to sort a list of custom objects by property type, however the C# LINQ syntax is KILLING me and I can't figure out how to convert it to VB

Class Foo
    Sub New(Name As String, Position As Integer)
        Me.Name = Name
        Me.Position = Position
    End Sub
    Public Name As String
    Public Position As Integer
End Class

Sub Main()
    Dim l As New List(Of Foo)
    l.Add(New Foo("C", 3))
    l.Add(New Foo("B", 2))
    l.Add(New Foo("A", 1))

    Dim asc = ..... (sort l by position asecnding)
    Dim desc = ..... (sort l by position descending)

End Sub

回答1:

Dim asc = From f In l Order By f.Position
Dim desc = From f In l Order By f.Position Descending


回答2:

I used c# to VB converter..

Dim sortedasc = l.OrderBy(Function(k) k.Position) 
Dim sorteddesc = l.OrderByDescending(Function(k) k.Position)

this should work..



标签: vb.net linq