views:

1077

answers:

1

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?

+5  A: 

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!

Michael La Voie