Chuckv Chuckv - 1 year ago 134 Question

LINQ Order BY using literal values in VB.NET?

I'm new to LINQ, would like to sort by a custom literal order... not sure of the syntax to do so (assuming it is possible). Thanks!

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("Something1", 1))
l.Add(New Foo("Something2", 2))
l.Add(New Foo("Something3", 3))

Dim literalSort = ..... 'sort l by this literal order... "2, 3, 1"

Answer Source

Adapting this answer to VB:

Dim order = New Integer() {2,3,1}

Dim literalSort = l.OrderBy(Function(i) If(order.Contains(i), 0, 1)) _ 
                   .ThenBy(Function(i) Array.IndexOf(order, i)) _
                   .ThenBy(Function(i) i)  ' sort rest numerically
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download