Max Bündchen
Max Bündchen

Reputation: 1362

Extension Linq OrderBy

I have an extension method to order in first place when a special condition is found.

public static IOrderedQueryable<TSource> OrderFirstIf<TSource>(this IQueryable<TSource> source, Func<TSource, bool> predicate)
    {
        return source.OrderBy(i => predicate(i) ? 0 : 1);
    }

The usage is:

db.where(...).OrderFirstIf(i => i.Code == code).ThenBy(...).ToList();

However I got the exception "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities".

How to use the predicate in this extension method?

Updated

public static IOrderedQueryable<TSource> OrderFirstIf<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
    return source.OrderBy(i => predicate(i) ? 0 : 1);
}

How to use the predicate in case of using Expression?

Upvotes: 0

Views: 83

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109109

First, predicate should be <Expression<Func<TSource, bool>>. But then you can't use source.OrderBy(i => predicate(i) ? 0 : 1) because it won't compile. The trick is to convert the predicate to a negated lambda expression:

public static IOrderedQueryable<TSource> OrderFirstIf<TSource>(this IQueryable<TSource> source, 
    Expression<Func<TSource, bool>> predicate)
{
    var negated = Expression.Not(predicate.Body);
    var negatedLambda = Expression.Lambda<Func<TSource, bool>>(negated, predicate.Parameters);
    return source.OrderBy(negatedLambda);
}

Upvotes: 1

Related Questions