2013-06-22 2 views
0

J'essaie d'implémenter le filtrage/la commande/la pagination sur un ensemble de données. Je veux filtrer par une chaîne de recherche, puis appliquer la commande, puis sélectionner un sous-ensemble de cet ensemble pour être une page.LINQ IEnumerable OrderBy

code ressemble à:

IEnumerable<Manufacturer> manufacturers; 

if (!String.IsNullOrEmpty(genericSearch)) 
{ 
    manufacturers = db.Manufacturers.Where(l => l.Name.Contains(genericSearch)); 
} 

manufacturers = manufacturers.OrderBy(sortColName, sortDir, true); // this won't build. it would 
// build if i put 'db.Manufacturers' before the .OrderBy but then i lose my filter. it would 
// also build if i used 'l => l.Name' as the OrderBy parameter but i only have the column name 
//as a string from the client. 

manufacturers.Skip(displayStart).Take(displayLength).ToList().ForEach(rec => aaData.Add 
(rec.PropertiesToList())); // this is paging where i can use ToList() 

Comment puis-je faire pour permettre de commander avec le nom de la colonne comme une chaîne?

+0

double possible de [Get Dynamic OrderBy dans LINQ] (http://stackoverflow.com/questions/16077490/get-dynamic-orderby-in-linq –

+0

Merci. Espérait une solution plus facile ou une approche alternative même. – user982119

+0

duplication possible de [dynamiquement trier avec LINQ] (http://stackoverflow.com/questions/4726047/dynamically-sorting-with-linq) – Hogan

Répondre

1

L'une des façons d'utiliser la réflexion

public static IEnumerable<T> Sort<T>(this IEnumerable<T> list, 
      string column, SortDirection direction = SortDirection.Ascending) 
    { 
     Func<T, object> selector = p => p.GetType().GetProperty(column).GetValue(p, null); 
     return (direction == SortDirection.Ascending 
        ? list.OrderBy(selector) 
        : list.OrderByDescending(selector) 
        ); 
    }