Sto creando un'origine dati fittizia su cui voglio essere in grado di passare in un elenco di SortExpressions.Come posso usare linq per ordinare per più campi?
public SortExpression(string name, SortDirection direction)
{
this.name = name;
this.direction = direction;
}
Aggiornamento con il codice di Jon Skeet e anche l'intera classe. GetData() sta compilando l'oggetto con il numero x di record.
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>();
}
}
Non sembra che stia facendo nulla. Compilazioni, nessun errore, solo nessun tipo. Qualche idea?
Sì, questo è il motivo per cui sto facendo il ciclo for invece del foreach, perché stavo pensando che avevo bisogno di un ThenBy lì da qualche parte. – rball
Ho appena risolto un bug, tra l'altro - hai bisogno della parte copyOfI altrimenti la variabile errata verrà catturata! –
Crap, ancora non funziona. – rball