2012-10-16 36 views
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(); 
+1

http://stackoverflow.com/questions/41244/dynamic-linq-orderby –

回答

4

在你的代码中实际的问题是,你只是得到PropertyInfo对象而不是属性值本身。要获得物业价值,您必须拨打PropertyInfo对象的GetValue()方法。

相关问题