如何动态地指定的LINQ排序依据的说法? [英] How do I specify the Linq OrderBy argument dynamically?

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

问题描述

我如何使用指定的值我采取作为参数传递给排序依据的说法?

例如:

 列表<的Student GT; existingStudends =新的List<的Student GT; {新的学生{...},新的学生{...}}

目前实现:

 列表<的Student GT; orderbyAddress = existingStudends.OrderBy(C => c.Address).ToList();

而不是 c.Address ,我怎么可以把它看作一个参数?

示例

 字符串参数=城;
 清单<的Student GT; orderbyAddress = existingStudends.OrderByDescending(C =>参数).ToList();


解决方案

下面是一个方法可行使用反射...

  VAR参数=地址;
VAR的PropertyInfo = typeof运算(学生).GetProperty(参数);
VAR orderByAddress = items.OrderBy(X => propertyInfo.GetValue(X,NULL));

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

Ex:

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

Currently implementation:

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

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

Example

 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排序依据的说法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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