简体   繁体   中英

How to dynamically add OrderBy() to an LINQ query

Is it possible to dynamically plug OrderBy(some_property) in linq?

So im dealing with a problem where i get column name and sort order eg {"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

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. 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.

(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) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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