1
可能重复:
Dynamic LINQ OrderBy将值传递给Linq中的OrderBy或OrderByDescending语句?
如何传递Linq中的一个值的排序依据或OrderByDescending声明?我试图动态地获得属性名称:
x.GetType().GetProperty(sortField)
这似乎并不奏效。有任何想法吗?
private void DynamicSort(ref List<Quote> myQuotes, String sortField, String direction)
{
if(direction == "ASC"){
this.grdViewDrafts.DataSource = myQuotes.OrderBy(x => x.GetType().GetProperty(sortField)).ToList();
}else{
this.grdViewDrafts.DataSource = myQuotes.OrderByDescending(x => x.GetType().GetProperty(sortField)).ToList();
}
}
解决方案:
this.grdViewDrafts.DataSource = myQuotes.OrderBy(x => x.GetType().GetProperty(sortField).GetValue(x, null)).ToList();
http://stackoverflow.com/questions/41244/dynamic-linq-orderby –