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);
}  

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2021-09-30
  • 2022-12-23
猜你喜欢
  • 2021-12-03
  • 2022-12-23
  • 2021-11-20
  • 2022-12-23
  • 2021-08-06
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案