I have a class derived from DynamicObject. I would like to sort that using a property (as passed to a BindingList ApplyCoreSort as a TypeDescriptor). I have tried a number of examples from here and other sites, but many of them are in C# and do not translate well to VB. I found the method from this MSDN blog to be nice and simple, but it fails when translated to VB:
Private Shared Function Sort(source As IEnumerable, [property] As String) As DynamicEntity()
Dim binder__1 = RuntimeBinder.Binder.GetMember(CSharpBinderFlags.None, [property], GetType(Example3), New CSharpArgumentInfo() {CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, Nothing)})
Dim param = Expression.Parameter(GetType(DynamicEntity), "o")
Dim getter = Expression.Dynamic(binder__1, GetType(Object), param)
Dim lambda = Expression.Lambda(Of Func(Of DynamicEntity, Object))(getter, param).Compile()
Return source.Cast(Of DynamicEntity)().OrderBy(lambda).ToArray()
End Function
Primarily because the original code relied on the dynamic type which the object type in VB cannot replace:
Func(Of DynamicEntity, Object)
vs
Func<DynamicObject, dynamic>
The C# equivalent is below:
private IEnumerable<DynamicObject> SortAscending(IEnumerable<DynamicObject> source, PropertyDescriptor property, ListSortDirection direction)
{
CallSiteBinder binder__1 = RuntimeBinder.Binder.GetMember(CSharpBinderFlags.None, property.Name, property.PropertyType, new CSharpArgumentInfo[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
ParameterExpression param = Expression.Parameter(typeof(DynamicObject), "o");
DynamicExpression getter = Expression.Dynamic(binder__1, property.PropertyType, param);
dynamic lambda = Expression.Lambda<Func<DynamicObject, dynamic>>(getter, param).Compile();
if (direction == ListSortDirection.Ascending) {
return source.Cast<DynamicObject>().OrderBy(lambda).ToList;
} else {
return source.Cast<DynamicObject>().OrderByDescending(lambda).ToList;
}
}
Unfortunately, translating it back to C# and putting it into another DLL does not work as the compiler complains that the IEnumerable type does not support OrderBy or OrderByDescending.
Can anyone suggest a way to get this working in VB or suggest an alternative example that actually works. Changing the dynamic to object does not work as the dynamic expression compiler refuses to compile the expression at runtime because a string is being returned rather than an object.
I have checked a number of examples and none of them seem to work correctly when trying to sort dynamic objects, and many of them won't compile in VS 2010 VB with .Net Framework 4. Even a way to get the above sort function to work in VB would be appreciated.