Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify LINQ's OrderBy direction as a boolean?

Tags:

c#

linq

I have a simple data class that has this signature:

internal interface IMyClass {
    string Letter { get; }
    int Number { get; }
}

I wish to be able to sort this data based on a field (specified as string sortField) and a direction (specified as bool isAscending)

Currently I am using a switch (with the ascending logic within each case as if)

IEnumerable<IMyClass> lst = new IMyClass[];//provided as paramater
switch (sortField)
{
    case "letter":
        if( isAscending ) {
            lst = lst.OrderBy( s => s.Letter );
        } else {
            lst = lst.OrderByDescending( s => s.Letter );
        }
        break;
    case "number":
        if( isAscending ) {
            lst = lst.OrderBy( s => s.Number );
        } else {
            lst = lst.OrderByDescending( s => s.Number );
        }
        break;
}

This is pretty ugly, for 2 properties, but when the sort logic differs it becomes a problem (we also see s => s.Number is duplicated twice in the code)

Question What is the best way to pass a boolean to choose the sort direction?

What I've Tried I've ripped apart System.Core.dll and found the OrderBy Extension method implementations:

OrderBy:

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
        this IEnumerable<TSource> source, 
        Func<TSource, TKey> keySelector
    ){

    return new OrderedEnumerable<TSource, TKey>(
        source, 
        keySelector, 
        null, 
        false
    );
}

OrderByDescending:

public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
        this IEnumerable<TSource> source, 
        Func<TSource, TKey> keySelector
    ){
        return new OrderedEnumerable<TSource, TKey>(
            source, 
            keySelector, 
            null, 
            true
        );
}

It appears the purpose of having 2 named methods is to abstract this boolean away. I can't create my own extension easily as OrderedEnumberable is internal to System.Core, and writing a layer to go from bool -> methodName -> bool seems wrong to me.

like image 973
James Avatar asked Aug 02 '12 16:08

James


People also ask

Is Boolean ordered?

Bools are sorted from false to true. The descending sort will order them from true to false. True is essentially equal to 1, and false to 0. Use boolean sorting for selection algorithms where some objects should be demoted.

What is difference between OrderBy and ThenBy in Linq?

Generally, ThenBy method is used with the OrderBy method. The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.

What is any in Linq c#?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.


4 Answers

I'd say write your own extension method:

public static IEnumerable<T> Order<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector, bool ascending)
{
    if (ascending)
    {
        return source.OrderBy(selector);
    }
    else
    {
        return source.OrderByDescending(selector);
    }
}

Then you can just write:

lst = lst.Order( s => s.Letter, isAscending );

As for specifying method name: I hope this doesn't come off as a cop-out answer, but I think you should stick with using a selector function instead of passing in a string. Going the string route doesn't really save you any typing or improve clarity (is "letter" really much faster or clearer than s => s.Letter?) and only makes your code fatter (you'd either need to maintain some sort of mapping from strings to selector functions or write custom parsing logic to convert between them) and possibly more fragile (if you go the latter route, there's a pretty high probability of bugs).

If your intention is to take a string from user input to customize sorting, of course, you have no choice and so feel free to disregard my discouraging remarks!


Edit: Since you are accepting user input, here's what I mean by mapping:

class CustomSorter
{
    static Dictionary<string, Func<IMyClass, object>> Selectors;

    static CustomSorter()
    {
        Selectors = new Dictionary<string, Func<IMyClass, object>>
        {
            { "letter", new Func<IMyClass, object>(x => x.Letter) },
            { "number", new Func<IMyClass, object>(x => x.Number) }
        };
    }

    public void Sort(IEnumerable<IMyClass> list, string sortField, bool isAscending)
    {
        Func<IMyClass, object> selector;
        if (!Selectors.TryGetValue(sortField, out selector))
        {
            throw new ArgumentException(string.Format("'{0}' is not a valid sort field.", sortField));
        }

        // Using extension method defined above.
        return list.Order(selector, isAscending);
    }
}

The above is clearly not as clever as dynamically generating expressions from strings and invoking them; and that could be considered a strength or a weakness depending on your preference and the team and culture you're a part of. In this particular case, I think I'd vote for the hand-rolled mapping as the dynamic expression route feels over-engineered.

like image 68
Dan Tao Avatar answered Oct 25 '22 07:10

Dan Tao


It's better to return IOrderedEnumerable in case you want to add further methods to the end. In that way the compiler will compile the entire chain as one expression.

public static class OrderByWithBooleanExtension
{
    public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, bool isAscending)
    {
        return isAscending ? source.OrderBy(keySelector) : source.OrderByDescending(keySelector);
    }
}
like image 29
M. Mennan Kara Avatar answered Oct 25 '22 08:10

M. Mennan Kara


I would have a look at the dynamic linq options described here by ScottGu

like image 21
CraftyFella Avatar answered Oct 25 '22 09:10

CraftyFella


You could implement your own extension that will order by a string property and support ascending and descending through a boolean, such as:

public static IOrderedQueryable<T> OrderByProperty<T>(this IQueryable<T> query, string memberName, bool ascending = true)
{
    var typeParams = new[] { Expression.Parameter(typeof(T), "") };

    var pi = typeof(T).GetProperty(memberName);
    string operation = ascending ? "OrderBy" : "OrderByDescending";
    return (IOrderedQueryable<T>)query.Provider.CreateQuery(
        Expression.Call(
            typeof(Queryable),
            operation,
            new[] { typeof(T), pi.PropertyType },
            query.Expression,
            Expression.Lambda(Expression.Property(typeParams[0], pi), typeParams))
    );
}
like image 40
Pablo Romeo Avatar answered Oct 25 '22 08:10

Pablo Romeo