2009-02-12 52 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()