LINQ到实体动态排序 [英] Linq-to-Entities Dynamic sorting

查看:149
本文介绍了LINQ到实体动态排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的查询,我该如何使用字符串作为排序依据的参数

This is my query, how can I use string as orderby parameter?

string sortColumn="Title";

var  items = (from ltem in ctxModel.Items
              where ltem.ItemID == vId
              orderby //something here
              select ltem).Skip(PageSize * PageIndex).Take(PageSize);



更新:结果
我不能只排序依据结果集,因为我的第一个的需要排序,只有的然后的页面。

UPDATE:
I can't just OrderBy the result set, because I FIRST need to sort, and only THEN to page.

推荐答案

其他人使用动态链接或其他建议库。 个人后,我就不会在图书馆的依赖带来了这样一个小任务。但是,你可以采取另外两种路径...

Others have suggested using Dynamic link or other libraries. Personally, I would not bring in a library dependency for such a small task. But two other paths that you can take are...


  • 使用的对象调用的语法和构建查询表达式树动态。例如...

  • Use Object Call syntax and build your query expression tree dynamically. For example...

请参阅的 http://blog.cincura.net/229310-sorting-in-iqueryable-using-string-as-column-name/

考虑延迟执行是非常重要的在这种情况下。您可以安全地建立您的查询返回的的IQueryable 的对象,然后运行该对象的对象查询排序。您的查询将只运行一次,当数据实际访问。

It is important to consider Deferred Execution in this scenario. You can safely build your query that returns an IQueryable object and then run a object query sort on that object. Your query will only be run once, when the data is actually accessed.

上面的博客文章是如何使用表达式API来构建和表达式树的例子您可以使用您的排序依据的。这真的只是听起来复杂。 MSDN文章可能是一个更好的参考。见如何:使用表达式树来构建动态查询MSDN上

The above blog post is an example of how you can use the Expression API to build and expression tree that you can use for your OrderBy. It really just sounds complicated. The MSDN article may be a better reference. See How to: Use Expression Trees to Build Dynamic Queries on MSDN.


  • 使用简单的路线,只使用一个交换机上的标题整个查询。

例如:

ItemType items = default(ItemType);
switch(sortColumn)
{
     case "Title":
     {
           items = ctxModel.Items
                    .Where(i => i.ItemID == vId)
                    .OrderBy( i => i.Title);
     }
     break;
 }

这篇关于LINQ到实体动态排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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