I've created an extension method which gets a property from an object and casts this to the required type.
See this code for the extension method "Select"
public static class DynamicQueryableExtensions
{
public static IEnumerable<TEntity> Select<TEntity>(this IEnumerable<object> source, string propertyName)
{
return source.Select(x => GetPropertyValue<TEntity>(x, propertyName));
}
private static T GetPropertyValue<T>(object self, string propertyName)
{
var type = self.GetType();
var propInfo = type.GetProperty(propertyName);
try
{
return propInfo != null ? (T)propInfo.GetValue(self, null) : default(T);
}
catch
{
return default(T);
}
}
}
The code is used as follows:
// This line will just work fine.
var employees = objects.Select<Employee>("XEmployee");
employees.Dump();
For a working example, see my KendoGridBinderEx project on github.