开发者

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

开发者 https://www.devze.com 2023-01-24 17:20 出处:网络
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

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开发者_如何学C!


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);


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号