可查询的两个或更多属性的顺序 [英] IQueryable order by two or more properties

查看:77
本文介绍了可查询的两个或更多属性的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用IQueryable OrderBy方法订购自定义对象的列表,如下所示:

I am currently ordering a list of custom objects using the IQueryable OrderBy method as follows:

mylist.AsQueryable().OrderBy("PropertyName");

现在,我希望按多个属性进行排序.有什么办法吗?

Now I am looking to sort by more than one property. Is there any way to do that?

谢谢, 扬尼斯

推荐答案

OrderBy(i => i.PropertyName).ThenBy(i => i.AnotherProperty)

在OrderBy和ThenBy中,您必须提供keySelector函数,该函数从对象中选择要排序的键.因此,如果您仅在运行时知道属性名称,则可以使用Reflection进行如下功能:

In OrderBy and ThenBy you have to provide keySelector function, which chooses key for sorting from object. So if you know property name only at runtime then you can make such function with Reflection like:

var propertyInfo = i.GetType().GetProperty("PropertyName"); 
var sortedList = myList.OrderBy(i => propertyInfo.GetValue(i, null)) 

但是它会比较慢,然后直接访问属性.您也可以使用Linq.Expressions快速编译"这样的函数,它的运行速度比反射快,但并不是很容易.或者,您可以在WPF中使用CollectionViewSource及其排序功能.

But it will be slower, then direct access to property. Also you can "compile" such function on the fly with Linq.Expressions and it will work faster than reflection but it is not very easy. Or you can use CollectionViewSource and their sorting ablilities in WPF.

也不要忘记OrderBy()返回可枚举的排序,并且它不会就地对您现有的List进行排序.在您的示例中,您没有将排序后的列表保存到变量中.

And don't forget that OrderBy() returns sorted enumerable and it does not sort your existed List inplace. In your example you did not save sorted list to variable.

这篇关于可查询的两个或更多属性的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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