zoukankan      html  css  js  c++  java
  • 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);
    }  
  • 相关阅读:
    mac OS 截图方法
    MAC OS上JAVA1.6 升级1.7,以及 maven3.2.1配置
    maven 安装设置方法
    STemWin移植
    uIP使用记录
    define宏定义细节及uCOS中宏定义技巧
    实验室播放视频步骤
    光通信零碎知识
    论文笔记6
    OFDMA
  • 原文地址:https://www.cnblogs.com/icyJ/p/OrderBy.html
Copyright © 2011-2022 走看看