如何动态指定 Linq OrderBy 参数? [英] How do I specify the Linq OrderBy argument dynamically?

查看:33
本文介绍了如何动态指定 Linq OrderBy 参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用作为参数的值指定传递给 orderby 的参数?

How do I specify the argument passed to orderby using a value I take as a parameter?

例如:

List<Student> existingStudends = new List<Student>{ new Student {...}, new Student {...}}

目前实施:

List<Student> orderbyAddress = existingStudends.OrderBy(c => c.Address).ToList();

代替c.Address,我如何将其作为参数?

Instead of c.Address, how can I take that as a parameter?

例子

 string param = "City";
 List<Student> orderbyAddress = existingStudends.OrderByDescending(c => param).ToList();

推荐答案

这是一个使用反射的可能性...

Here's a possiblity using reflection...

var param = "Address";    
var propertyInfo = typeof(Student).GetProperty(param);    
var orderByAddress = items.OrderBy(x => propertyInfo.GetValue(x, null));

这篇关于如何动态指定 Linq OrderBy 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆