Estoy creando una fuente de datos simulada que deseo poder pasar en una lista de SortExpressions.¿Cómo puedo usar linq para ordenar por varios campos?
public SortExpression(string name, SortDirection direction)
{
this.name = name;
this.direction = direction;
}
actualización con código de Jon Skeet y también a toda la clase. GetData() solo está llenando el objeto con x cantidad de registros.
public class Data
{
public int Id { get; set; }
public Guid gId { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public DateTime Created { get; set; }
public string SortMe { get; set; }
public static List<Data> GetFakeData(int start, int numberToFetch, IList<SortExpression> sortExpressions, IList<FilterExpression> filterExpressions, out int totalRecords)
{
DataCollection items = GetData();
IEnumerable<Data> query = from item in items select item;
bool sortExpressionsExist = sortExpressions != null;
if (sortExpressionsExist)
{
// Won't be read in the first iteration; will be written to
IOrderedEnumerable<Data> orderedQuery = null;
for (int i = 0; i < sortExpressions.Count; i++)
{
// Avoid single variable being captured: capture one per iteration.
// Evil bug which would be really hard to find :)
int copyOfI = i;
// Tailor "object" depending on what GetProperty returns.
Func<Data, object> expression = item =>
item.GetType().GetProperty(sortExpressions[copyOfI].Name);
if (sortExpressions[i].Direction == SortDirection.Ascending)
{
orderedQuery = (i == 0) ? query.OrderBy(expression)
: orderedQuery.ThenBy(expression);
}
else
{
orderedQuery = (i == 0) ? query.OrderByDescending(expression)
: orderedQuery.ThenByDescending(expression);
}
}
query = orderedQuery;
}
bool filterExpressionsExist = filterExpressions != null;
if (filterExpressionsExist)
{
foreach (var filterExpression in filterExpressions)
{
query.Where(item => item.GetType().GetProperty(filterExpression.ColumnName).GetValue(item, null).ToString().Contains(filterExpression.Text));
}
}
totalRecords = query.Count();
return query.Skip(start).Take(numberToFetch).ToList<Data>();
}
}
Parece que no hace nada. Compila, sin errores, simplemente no ordena. ¿Algunas ideas?
Sí, es por eso que estoy haciendo el bucle en lugar del foreach, porque estaba pensando que necesitaba un ThenBy en algún lugar. – rball
Acabo de corregir un error, por cierto, necesitas la parte copyOfI ya que de lo contrario se capturará la variable incorrecta. –
Mierda, todavía no está funcionando. – rball