简体   繁体   English

如何将 OrderBy() 动态添加到 LINQ 查询

[英]How to dynamically add OrderBy() to an LINQ query

Is it possible to dynamically plug OrderBy(some_property) in linq?是否可以在 linq 中动态插入 OrderBy(some_property)?

So im dealing with a problem where i get column name and sort order eg {"EmployeeName", "asc"} OR {"EmployeeName","desc"}所以我正在处理一个我得到列名和排序顺序的问题,例如 {"EmployeeName", "asc"} OR {"EmployeeName","desc"}

During run time my code will be like as follows without user demanded column & its sort order.在运行时,我的代码将如下所示,没有用户要求的列及其排序顺序。

var dbEmployees = await _dbContext.Employees
.AsNoTracking()
.Take(10)

But if we now get an column & sort order code should now have OrderBy() in place like as follows但是如果我们现在得到一个列和排序顺序代码现在应该有 OrderBy() 如下所示

var dbEmployees = await _dbContext.Employees    
.AsNoTracking()
.OrderBy(x => x.EmployeeName)
.Take(10)

Is it possible to do so?有可能这样做吗?

Any help or pointers are welcomed.欢迎任何帮助或指点。

Remember, you can do your Linq stuff in a single fluent expression, but you are not forced to.请记住,您可以用一个流利的表达式来完成您的 Linq 的工作,但您并非被迫这样做。 You can actually split the second code example you gave into a sequence of three separate assignments which in its entirety is functionally equivalent to your second code example:您实际上可以将您给出的第二个代码示例拆分为三个单独的分配序列,它们在功能上与您的第二个代码示例完全等效:

var dbEmployees = await _dbContext.Employees.AsNoTracking();
dbEmployees = dbEmployees.OrderBy(x => x.EmployeeName);
dbEmployees = dbEmployees.Take(10);

It should now be clear that all else you need is to make the second assignment (the one with the OrderBy) conditional in some way that fits your program logic.现在应该很清楚,您需要做的所有其他事情就是以某种适合您的程序逻辑的方式使第二个赋值(带有 OrderBy 的那个)有条件。

(And depending on your particular program structure and design, you could perhaps even relocate the whole conditional application of OrderBy on the dbEmployees enumerable into an extension method in a way that would allow you to keep using fluent coding style like await _dbContext.Employees.AsNoTracking().ApplyConditionalOrderBy().Take(10) ) (并且根据您的特定程序结构和设计,您甚至可以将可枚举的dbEmployees上的 OrderBy 的整个条件应用程序重新定位到扩展方法中,这样您就可以继续使用流畅的编码风格,例如await _dbContext.Employees.AsNoTracking().ApplyConditionalOrderBy().Take(10) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM