2012-10-16 33 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()方法。

相關問題