日期:2014-05-20  浏览次数:20708 次

如何动态指定排序字段
var souce=ataSouce.OrderByDescending(o => o.ID)

其中o.ID是不定的,还有很多字段,比如o.Name, o.Age等等,现在我能通过用户的操作得到想排序的字段
string dataOrderBy= "o.xx"; 其中xx动态获得,我想要达得以下面这种突起果:

var souce=ataSouce.OrderByDescending(o => dataOrderBy)

应该如何实现呢?

PS:类似于需要C中的宏替换功能,但C#中没有,希望得到好的变通方法,谢谢。

------解决方案--------------------

string dataOrderBy= "o.xx"; 

var souce=ataSouce.OrderByDescending(o => GetPropertyValue(o,dataOrderBy));

private static object GetPropertyValue(object obj, string property)
{
System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}


http://blog.csdn.net/q107770540/article/details/6133484