Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL extension method for sorting and paging

I have found an extension method that handles sorting and paging for LINQ. While this works well, I am trying to see if there are some other ways I can use this.

At present, the code for the extension method is as follows:

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

The method takes in an expression, which is based off the type.

In my Dealer class, I have a method GetDealers, which essentially calls this, i.e.

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

From the presentation side of things though, I do not know or can access the expression as above, e.g.

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

The only way is to have a switch statement in my GetDealers method that would then convert to the expression. Is there a way to bypass this, or is this method OK?

like image 384
mickyjtwin Avatar asked Feb 12 '09 23:02

mickyjtwin


People also ask

Which LINQ methods should you use to implement pagination?

We can implement the paging using the Linq Skip and Take method.

Does LINQ use extension methods?

Short answer: Yes, you can use a custom extension method inside a LINQ query - but you cannot use an extension method that the underlying data provider does not know how to execute. LINQ stands for Language-Integrated-Query, and is a language feature in C#. You can use any . NET method in a LINQ query.


1 Answers

I'm not exactly sure what you're asking, but I believe it's something that I have looked into myself. If you would like to know how to dynamically sort your results based on a string, rather than a proper LINQ expression, then you're in luck.

Scott Guthrie published a great article on that very topic. It references a Microsoft file which extends any IQueryable object to support dynamic sorting. C# Dynamic Query Library (included in the \LinqSamples\DynamicQuery directory). Just add the page to your App_Code folder and include "Using System.Linq.Dynamic" in your project and you will be able to use the following syntax:

myUsers = myUsers.OrderBy("LastName");

I hope this helps!

like image 161
Michael La Voie Avatar answered Oct 01 '22 18:10

Michael La Voie