linq orderby使用属性名称字符串 [英] linq orderby using property name string

查看:455
本文介绍了linq orderby使用属性名称字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要订购的清单.

I have a list which I need to order eg.

var list = someelements;

我还有一个参数,该参数指示应按哪个属性和哪个方向订购列表数据,例如.

I also have a parameter which says by which property and what direction I should order list data eg.

var sortby = "Name";
var sortdirection = "desc";

我想知道是否可以将字符串属性名称与正确的属性匹配,以便得到:

I was wondering if I can match string property name with the right property so I get:

var list = someelements.OrderBy(x => x.Name).ToList();

sortby == "Name"时无需使用切换循环来检查属性名称并将正确的属性分配给OrderBy.

when sortby == "Name" without the need of using switch loop to check property name and assign a correct property to OrderBy.

我想通过选择OrderByOrderByDescending来实现同样的效果,具体取决于我得到的是sortdirection = "asc"还是sortdirection = "desc"

Same I would like to achieve with select either OrderBy or OrderByDescending depending whether I get sortdirection = "asc" or sortdirection = "desc"

有可能吗?如果可以,怎么办?

Is it possible and if yes, how?

推荐答案

您可以通过Nuget获取Dynamic Linq.然后,您可以使用.OrderBy(sortby + " " + sortdirection). 这是链接:动态Linq .

You can get Dynamic Linq through Nuget. Then you can use .OrderBy(sortby + " " + sortdirection). Here is the link: Dynamic Linq.

这篇关于linq orderby使用属性名称字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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