Help With Generic LINQ OrderBy Lambda Expression
Asked Answered
D

2

-1

Trying to get an OrderBy on an IQueryable to work, not having much luck.

Here's my method:

public ICollection<T> FindAll<T>(Expression<Func<T,bool>> predicate, Expression<Func<T,int>> orderingKey) where T : Post
{
    return repository
             .Find()
             .Where(predicate)
             .OfType<T>()
             .OrderBy(orderingKey)
             .ToPagedList();
}

The ordering works if i do this:

FindAll(p => p.PostName == "Foo", p => p.PostId);

But not if i want to do this:

FindAll(p => p.PostName == "Foo", p => p.DateModified);

It doesn't work of course, because i have declared the Expression as T,int, whereas the above expression is of type T,DateTime

How do i declare it so i can OrderBy any property of my entity (Post)?

This is LINQ-Entities (Entity Framework 4.0).

Defamation answered 30/9, 2010 at 7:21 Comment(1)
Take a look at [this answer][1] Cheers [1]: https://mcmap.net/q/1008445/-problem-with-generic-linq-orderby-functionLoraine
S
4

Queryable.OrderBy takes a key selector with the following type:

Expression<Func<TSource, TKey> keySelector>

If you change orderingKey to an expression of this type then it will work. You will also need to add another type parameter.

public ICollection<T> FindAll<T, TKey>(
    Expression<Func<T, bool>> predicate,
    Expression<Func<T, TKey>> orderingKey
) where T : Post
Sladen answered 30/9, 2010 at 7:24 Comment(2)
so a) what do i change my method declaration to, and b) how do i change the usage?Defamation
@RPM1984: You don't have to change the usage.Sladen
S
0

You would have to at least have a generic parameter type defined for the ordering key. Instead of returning int, return a generic type.

e.g.,

public ICollection<TPost> FindAll<TPost,TOrder>(Expression<Func<TPost,bool>> predicate, Expression<Func<TPost,TOrder>> orderingKey) where TPost : Post
{
    return repository
             .Find()
             .Where(predicate)
             .OfType<TPost>()
             .OrderBy(orderingKey)
             .ToPagedList();
}
Since answered 30/9, 2010 at 7:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.