如何将IOrderedQueryable传递给方法并将其追加到查询中

时间:2013-07-28 01:39:29

标签: c# linq-to-entities

如何将一个或多个lambda order by子句传递给方法并将其附加到linq to entities查询,如下所示?我不想传入字符串,我之前已经讨论过,它应该是lambda表达式,用于可维护性/重构/编译支持。

public IList<UserRating> GetUserRatings(int userId, IPager pager, IOrderedQueryable<UserRating> orderBy)
{
    return _userRatingRepository.Table.Where(a => a.UserId == userId).Skip(pager.Skip).Take(pager.PageSize). /* orderBy goes here */ .ToList();
}

1 个答案:

答案 0 :(得分:1)

继承人我是怎么做到的:

public IList<UserRating> GetUserRatings<TKey>(
    int userId, 
    IPager pager, 
    Func<UserRating, TKey> orderBy)
{
    return _userRatingRepository
        .Table
        .Where(a => a.UserId == userId)
        .Skip(pager.Skip)
        .Take(pager.PageSize)
        .OrderBy(orderBy)
        .ToList();
}

用法:

GetUserRatings(1,pager, u=> u.Id)