Elger Mensonides
Elger Mensonides

Reputation: 7029

LINQ sorting: Cannot order by type 'System.IComparable'

I'm building a small search class that uses predicatebuilder to get some results:

here is my query:

var results = (from u in db.users
               join p in db.profiles on u.userId equals p.UserID
               select new SearchResult { Profile = p, User = u }).AsQueryable().Where(predicate);

Results become an enumerable of SearchResult:

public class SearchResult 
{
    public user User { get; set; }
    public profile Profile { get; set; }
}

This works fine but now I also want to sort it:

var sortedResult = results.OrderBy(x => x.User.timeAdded);

And this works fine too except when I do:

Expression<Func<SearchResult, IComparable>> OrderByExpression = x => x.User.timeAdded;
var sortedResult = results.OrderBy(OrderByExpression);

I get this error: Cannot order by type 'System.IComparable'.

Isn't this exactly the same as putting the lambda query right into the orderby clause (which works) ? The reason why I doing this is that I want to pass the orderby expression to another function.

Anyone knows what I'm doing wrong? Thanks!

Upvotes: 1

Views: 2278

Answers (2)

Julien Lebosquain
Julien Lebosquain

Reputation: 41243

OrderBy expects an expression of type Expression<Func<TSource, TResult>>. In your code, TSource is SearchResult and TResult is IComparable, which can't be translated to a DB query. You want TResult to be a primitive type equals to the concrete type of timeAdded, (given the name, I assume it's a DateTime?) for this to work.

Expression<Func<SearchResult, DateTime>> OrderByExpression = x => x.User.timeAdded;
var sortedResult = results.OrderBy(OrderByExpression);

Upvotes: 1

Jakub Konecki
Jakub Konecki

Reputation: 46008

Have you tried (no access to VS right now, so it's more of a guess):

Func<SearchResult, IComparable> OrderByFunc = x => x.User.timeAdded;
var sortedResult = results.OrderBy(OrderByFunc);

Upvotes: 0

Related Questions