Cedric Krause
Cedric Krause

Reputation: 381

VisualBasic order List by Property as String

I've got an List of an Custom Class and want to order this List by an Property, but I only have the String of the Property name, becasue I recive this from an javascript. I tried this with System.Reflection, but it seem, that it isn't working:

Dim l As List(Of ActionElement) = New List(Of ActionElement)
'Fill the list
l = l.OrderBy(Function(x) GetType(ActionElement).GetProperty("Designation")).ToList()

Upvotes: 1

Views: 113

Answers (1)

rclement
rclement

Reputation: 1714

This will get you to what you want:

Dim l As List(Of ActionElement) = New List(Of ActionElement)
'Fill the list
l = l.OrderBy(Function(x) GetType(ActionElement).GetProperty("Designation").GetValue(x).ToString()).ToList()

I would change it slightly to reduce operations to:

Dim l As List(Of ActionElement) = New List(Of ActionElement)
Dim sortProperty as PropertyInfo = GetType(ActionElement).GetProperty("Designation")

'Fill the list
l = l.OrderBy(Function(x) sortProperty.GetValue(x).ToString()).ToList()

Upvotes: 3

Related Questions