可能重复:
动态 LINQ OrderBy
如何将值传递给 Linq 中的 OrderBy 或 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();