How can i make an extension method that will work like this
public static class Extensions<T>
{
public static IQueryable<T> Sort(this IQueryable<T> query, string sortField, SortDirection direction)
{
// System.Type dataSourceType = query.GetType();
//System.Type dataItemType = typeof(object);
//if (dataSourceType.HasElementType)
//{
// dataItemType = dataSourceType.GetElementType();
//}
//else if (dataSourceType.IsGenericType)
//{
// dataItemType = dataSourceType.GetGenericArguments()[0];
//}
//var fieldType = dataItemType.GetProperty(sortField);
if (direction == SortDirection.Ascending)
return query.OrderBy(s => s.GetType().GetProperty(sortField));
return query.OrderByDescending(s => s.GetType().GetProperty(sortField));
}
}
Currently that says “Extension methods must be defined in a non-generic static class”.
How do i do this?
Try this… (but I’m not sure it will do what you want.)
… The generic parameter should be on the method and not on the class. Moving it from
Extensions<T>toSort<T>(would allow you to get rid of the compiler error you are having.As for what you are trying to do with reflection, you would be returning a PropertyInfo object for the orderby clause. This is most likely not compable with the expression tree that you want. You may want to look at Dynamic LINQ.
… this is an extract from Dynamic LINQ.