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



可能的重复项:
动态 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(); 

代码中的实际问题是你只得到PropertyInfo对象,而不是属性值本身。若要获取属性值GetValue()必须调用PropertyInfo对象的方法。

最新更新