Emi
Emi

Reputation: 306

Sorting a list of ExpanoObejct by the properties using reflection

I want to sort a List(Of MyDynamicObject) by it's properties, where MyDynamicObject is an ExpandoObject. I have the property names as strings, so I need to use some sort of reflection to pass them.

Let's say I have a list:

MyList = New List(Of Entry)

where Entry has a property MyProperty_01.
Now I want to sort MyList by the objects property MyProperty_01.

In case of static objects and no reflection, I would do something like this this:

MyList = MyList.OrderBy(Function(x) x.MyProperty_01).ToList

Now if I need to pass the property name as a string, I can do this:

Dim MyPropertyName As String = "MyProperty_01"
MyList = MyList.OrderBy(Function(x) GetType(Entry).GetProperty(MyPropertyName).GetValue(x)).ToList

where Entry is the objects class reference.

How can I do this with an ExpandoObject? I don't have a class reference in case of an ExpandoObject.

So this doesn't work anymore.

Dim MyPropertyName As String = "MyProperty01"
MyList = MyList.OrderBy(Function(x) GetType().GetProperty(MyPropertyName).GetValue(x)).ToList

Upvotes: 1

Views: 308

Answers (1)

har07
har07

Reputation: 89305

This is one possible way, but not using reflection. Since ExpandoObject implements IDictionary(Of String, Object).Item interface, you can cast the object to that interface type and access properties by property name string, just like you access value by the corresponding string key from a dictionary :

Dim MyPropertyName As String = "MyProperty01"
MyList = MyList.OrderBy(Function(x) CType(x, IDictionary(Of String, Object))(MyPropertyName)).ToList

Upvotes: 1

Related Questions