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 –