Pass a value to an OrderBy or OrderByDescending statement in Linq?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Dynamic LINQ OrderBy
如何在LINQ中将值传递给orderby或orderbyDescending语句?我正在尝试动态获取属性名:
1 | x.GetType().GetProperty(sortField) |
这似乎不起作用。有什么想法吗?
1 2 3 4 5 6 7 8 9 | 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(); } } |
解决方案:
1 | this.grdViewDrafts.DataSource = myQuotes.OrderBy(x => x.GetType().GetProperty(sortField).GetValue(x, null)).ToList(); |
代码中的实际问题是,您只得到