orderBy 传入属性的字符串

IEnumerable下面的的OrderBy可以用于集合的排序。

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

他需要传入一个代理,即通过数据返回排序Key的代理。

常见的用法:

var s = new List<Student>();
s.Add(new Student(1, "AAA", 10));
s.Add(new Student(2, "BBB", 9));
s.Add(new Student(3, "CCC", 8));
s.Add(new Student(4, "DDD", 11));
var query = s.OrderBy(x =>x.Age);
foreach (var item in query)
    Console.WriteLine(item);

现在是另一种情况,已知的是Student的属性名称"Age",怎么对s排序呢。

方法是:通过反射获取属性相对应的属性值。

//排序
s.OrderBy(x => GetPropertyValue(x, "Age"))

//函数支持
private static object GetPropertyValue(object obj, string property)
{
    PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
    return propertyInfo.GetValue(obj, null);
}  
posted @ 2013-12-31 10:35  脸谱匠  阅读(1769)  评论(0编辑  收藏  举报