LINQ运行时OrderBy [英] LINQ runtime OrderBy

查看:78
本文介绍了LINQ运行时OrderBy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有列表< MyObjecT> 我希望能够在运行时进行排序。我想这样做,没有巨人 IF 声明



I have a List<MyObjecT> that I would like to be able to sort at run-time. I wanto to do this, without the giant IF statement

private List<Customer> SortCustomer(string sortBy, string sortOrder)
{
   // obviously I get this from a service in the real code
   var myList = new List<Customer>();

   if (sortBy == "firstname" && sortOrder == "asc") {
       return myList.OrderBy(x => x.FirstName);
   } else if (sortBy == "firstname" && sortOrder == "desc") {
       return myList.OrderByDesc(x => x.firstName);
   } else if ..... // you get the idea

}





我不能轻易地在数据库中排序(其中一个字段是以字符串形式存储的十进制数,另一个是查找字段,但数据库中没有查找表它只是一个没有引用的int字段。我不想处理根据需要转换db字段来进行排序。



我也可以'不要使用Dynamic Linq库,只是为了让事情变得更复杂。



任何想法?



谢谢,

Andrew



I can''t sort in the database easily (one of the fields is a decimal stored as string, another is a lookup field, but there''s no lookup table so in the database it is just an int field with no reference. I didn''t want to deal with trying to convert the db fields as necessary to sort.

I also can''t use the Dynamic Linq Library, just to make things more complicated.

Any ideas?

Thanks,
Andrew

推荐答案

您可以编写自己的比较器来实现 IComparer [ ^ ]。这是一个例子: http://www.atlanticbt.com/blog/sorting -with-linq-to-objects / [ ^ ]



只需在比较器中编写所有案例代码,并传递要使用的参数(属性名称,顺序)构造函数。您可以使用基本反射根据其名称访问属性。但我不确定,你会获得多少 - 但至少是更清晰的代码。
You could write your own comparer implementing IComparer[^]. Here is an example: http://www.atlanticbt.com/blog/sorting-with-linq-to-objects/[^]

Just code all your cases in the comparer, and pass the parameters to be used (property name, order) in the constructor. You can use basic reflection to access properties based on their name. But I am not sure, that you will gain much - but clearer code at least.


这篇关于LINQ运行时OrderBy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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