2009-02-12 50 views
7

我发现了一个处理排序和分页的扩展方法,用于LINQ。虽然这很有效,但我试图看看是否有其他方法可以使用。用于排序和分页的LINQ to SQL扩展方法

目前,对于extension method的代码如下:

public static IQueryable<T> Page<T, TResult>(
    this IQueryable<T> obj, 
    int page, 
    int pageSize, 
    System.Linq.Expressions.Expression<Func<T, TResult>> keySelector, 
    bool asc, 
    out int rowsCount) 
{ 
    rowsCount = obj.Count(); 

    int innerRows = (page - 1) * pageSize; 

    if (asc) 
     return obj.OrderBy(keySelector).Skip(innerRows).Take(pageSize).AsQueryable(); 
    else 
     return obj.OrderByDescending(keySelector).Skip(innerRows).Take(pageSize).AsQueryable(); 
} 

该方法将在表达式中,这是基于关闭的类型。

以我经销商类,我有一个方法GetDealers,其基本上调用此, 即

db.User.Page(1, 2, p => p.User.UserProperty.Name, true, out rowCount) 

从事物呈现侧虽然,我不知道或可以访问的表达如上述,例如

ListView1.DataSource = users.GetDealers("SortColumn", pageNo, pageSize, out rowCount, bool asc); 
ListView1.DataBind(); 

唯一的方法是在我的GetDealers方法中有一个switch语句,然后它将转换为表达式。有没有办法绕过这个,或者这个方法好吗?

回答

5

我不完全确定你在问什么,但我相信这是我自己研究过的东西。如果你想知道如何根据一个字符串动态地对结果进行排序,而不是一个合适的LINQ表达式,那么你很幸运。

Scott Guthrie在那个话题上发表了很棒的article。它引用了一个Microsoft文件,该文件扩展了任何支持动态排序的对象IQueryableC# Dynamic Query Library (included in the \LinqSamples\DynamicQuery directory)。只是网页添加到您的App_Code文件夹,并在项目中包含“使用System.Linq.Dynamic”,您将能够使用的语法如下:

myUsers = myUsers.OrderBy("LastName"); 

我希望这有助于!

0

如果您正在寻找扩展方法来对所有类型的工作

public static class SortingAndPagingHelper 
{ 
    /// <summary> 
    /// Returns the list of items of type on which method called 
    /// </summary> 
    /// <typeparam name="TSource">This helper can be invoked on IEnumerable type.</typeparam> 
    /// <param name="source">instance on which this helper is invoked.</param> 
    /// <param name="sortingModal">Page no</param> 
    /// <returns>List of items after query being executed on</returns> 
    public static IEnumerable<TSource> SortingAndPaging<TSource>(this IEnumerable<TSource> source, SortingAndPagingInfo sortingModal) 
    { 
     // Gets the coloumn name that sorting to be done o`enter code here`n 
     PropertyInfo propertyInfo = source.GetType().GetGenericArguments()[0].GetProperty(sortingModal.SortColumnName); 

     // sorts by ascending if sort criteria is Ascending otherwise sorts descending 
     return sortingModal.SortOrder == "Ascending" ? source.OrderByDescending(x => propertyInfo.GetValue(x, null)).Skip(sortingModal.PageSelected * sortingModal.PageSize).Take(sortingModal.PageSize) 
          : source.OrderBy(x => propertyInfo.GetValue(x, null)).Skip(sortingModal.PageSelected * sortingModal.PageSize).Take(sortingModal.PageSize); 
    } 
} 

DbContext dbContext = new DbContext(); dbContext.rainingSessions.Where(x => x.RegistrationDeadline > DateTime.Now) .SortingAndPaging(sortAndPagingInfo).ToList()