score:17

Accepted answer

try this... (but i'm not sure it will do what you want.)

public static class extensions
{ 
    public static iqueryable<t> sort<t>(this iqueryable<t> query, 
                                             string sortfield, 
                                             sortdirection direction) 
    { 
        if (direction == sortdirection.ascending) 
            return query.orderby(s => s.gettype()
                                       .getproperty(sortfield)); 
        return query.orderbydescending(s => s.gettype()
                                             .getproperty(sortfield)); 

    } 
} 

... the generic parameter should be on the method and not on the class. moving it from extensions<t> to sort<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.

public static iqueryable orderby(this iqueryable source, 
                                      string ordering, 
                                      params object[] values) {
    if (source == null) throw new argumentnullexception("source");
    if (ordering == null) throw new argumentnullexception("ordering");
    parameterexpression[] parameters = new parameterexpression[] {
        expression.parameter(source.elementtype, "") };
    expressionparser parser = new expressionparser(parameters, 
                                                   ordering, 
                                                   values);
    ienumerable<dynamicordering> orderings = parser.parseordering();
    expression queryexpr = source.expression;
    string methodasc = "orderby";
    string methoddesc = "orderbydescending";
    foreach (dynamicordering o in orderings) {
        queryexpr = expression.call(
            typeof(queryable), o.ascending ? methodasc : methoddesc,
            new type[] { source.elementtype, o.selector.type },
            queryexpr, expression.quote(expression.lambda(o.selector, 
                                                          parameters)));
        methodasc = "thenby";
        methoddesc = "thenbydescending";
    }
    return source.provider.createquery(queryexpr);
}

score:3

the error already tells you:

extension methods must be defined in a non-generic static class.

simply remove the generic type argument.

public static class extensions // no <t>
{
    // ...
}

score:8

change this:

public static class extensions
{
    public static iqueryable<t> sort<t>(this iqueryable<t> query, string sortfield, sortdirection direction)
    {
      //code
    }
}

the class needs to be non-generic, just your extension method should be :)


Related Query

More Query from same tag