2010-10-15 2 views
8

У меня есть методСортировка Gridview с платформой Entity.

private void BindGrid() 
{ 
    dataContext = new VTCEntities(); 
    string SortExpression = "DisplayName"; 
    string SortDirection = "ASC"; 
    int skip = 0; 

    if (this.ViewState["SortExp"] != null) 
    { 
     SortExpression = this.ViewState["SortExp"].ToString(); 
    } 

    if (this.ViewState["SortOrder"] != null) 
    { 
     string d = this.ViewState["SortOrder"].ToString(); 
     if (d == "ASC") 
     { 
      SortDirection = "ASC"; 
     } 
     else 
     { 
      SortDirection = "DESC"; 
     } 
    } 

    if (CurrentPage != 0) 
    { 
     skip = CurrentPage * PageSize; 
    } 

    if (SortDirection == "ASC") 
    { 
     this.grdCustomers.DataSource = dataContext.CustomerSet.OrderBy(i => i.DisplayName).Skip(skip).Take(PageSize); 
    } 
    else 
    { 
     this.grdCustomers.DataSource = dataContext.CustomerSet.OrderByDescending(i => i.DisplayName).Skip(skip).Take(PageSize); 
    } 

    this.grdCustomers.DataBind(); 
} 

и он начинает пахнуть, плохо. У меня есть 4 столбца, которые я должен сортировать. Я бы хотел, чтобы я не делал переключения или что-то, чтобы определить, какое свойство на CustomerSet я пытаюсь заказать. Что мог бы сделать лучший программист, чтобы связать SortExpression, которая является строкой, для свойства на одном из объектов CustomerSet?

Спасибо, что и всегда.
Джим

ответ

10

Я использовал этот метод расширения для этого в прошлом:

public static class QueryExtensions { 
    public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName) { 
     if (source == null) { 
      throw new ArgumentNullException("source"); 
     } 

     // DataSource control passes the sort parameter with a direction 
     // if the direction is descending   
     int descIndex = propertyName.IndexOf(" DESC"); 

     if (descIndex >= 0) { 
      propertyName = propertyName.Substring(0, descIndex).Trim(); 
     } 

     if (String.IsNullOrEmpty(propertyName)) { 
      return source; 
     } 

     ParameterExpression parameter = Expression.Parameter(source.ElementType, String.Empty); 
     MemberExpression property = Expression.Property(parameter, propertyName); 
     LambdaExpression lambda = Expression.Lambda(property, parameter); 

     string methodName = (descIndex < 0) ? "OrderBy" : "OrderByDescending"; 

     Expression methodCallExpression = Expression.Call(typeof(Queryable), methodName, 
              new Type[] { source.ElementType, property.Type }, 
              source.Expression, Expression.Quote(lambda)); 

     return source.Provider.CreateQuery<T>(methodCallExpression); 
    } 
} 

Источник: http://weblogs.asp.net/davidfowler/archive/2008/12/11/dynamic-sorting-with-linq.aspx

Тогда можно переписать так:

 if (SortDirection == "ASC") 
     { 
      this.grdCustomers.DataSource = dataContext.CustomerSet.OrderBy(i => i.DisplayName).Skip(skip).Take(PageSize); 
     } 
     else 
     { 
      this.grdCustomers.DataSource = dataContext.CustomerSet.OrderByDescending(i => i.DisplayName).Skip(skip).Take(PageSize); 
     } 

в

this.grdCustomers.DataSource = dataContext.CustomerSet.SortBy("DisplayName DESC").Skip(skip).Take(PageSize); 
+3

bendewey, вы такие деньги, что даже не знаете, как вы стоите ... спасибо за пучок в правильном направлении. – jim

+0

это отличное решение. Благодарю. –

Смежные вопросы