为什么此方法不对列表中的值进行排序?
public Paging(IEnumerable<T> values, int start, int limit, string property, string dir)
{
this.Total = values.Count();
Func<T, string> func = a => a.GetType().GetProperty(property).Name;
IEnumerable<T> order = null;
if (dir == "DESC")
order = values.OrderByDescending(func);
else
order = values.OrderBy(func);
if ((start + limit) > this.Total)
limit = this.Total - start;
IEnumerable<T> items = (start < 0 || limit < 0) ? order : order.Skip(start).Take(limit);
this.AddRange(items);
}
答案 0 :(得分:1)
您正在按属性名称进行排序,该名称对于集合中的每个元素都是相同的。此表达式将始终返回property
。
a => a.GetType().GetProperty(property).Name
如果按整个集合中的表达式排序,它就没有效果。
无论如何,在排序中使用反射是一个非常糟糕的主意,因为它将导致执行排序的极端开销。我建议使用Dynamic LINQ,它具有内置功能,可以按名称给出的属性进行排序。
如果将Dynamic LINQ库添加到项目中,您可以改为编写:
if (dir == "DESC")
order = values.OrderBy(property + " DESC");
else
order = values.OrderBy(property);