Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of <Object> with VB and LINQ

Tags:

vb.net

linq

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
like image 972
WhiskerBiscuit Avatar asked Mar 01 '12 16:03

WhiskerBiscuit


People also ask

How do I sort in LINQ?

LINQ includes five sorting operators: OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse. LINQ query syntax does not support OrderByDescending, ThenBy, ThenByDescending and Reverse. It only supports 'Order By' clause with 'ascending' and 'descending' sorting direction.

How would you sort the list in ascending order LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

How do I get data in descending order in LINQ?

OrderByDescending Operator If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.


2 Answers

Dim asc = From f In l Order By f.Position
Dim desc = From f In l Order By f.Position Descending
like image 123
harriyott Avatar answered Oct 22 '22 06:10

harriyott


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..

like image 13
AnarchistGeek Avatar answered Oct 22 '22 07:10

AnarchistGeek