Skip to main content
 首页 » 编程设计

c#之将值传递给 Linq 中的 OrderBy 或 OrderByDescending 语句

2024年02月20日12kerrycode

<分区>

Possible Duplicate:
Dynamic 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();