Order LINQ by “string” name

我的未来我决定 提交于 2019-12-21 12:41:47

问题


PROBLEM SOLVED!!!

The solution is Linq.Dynamic

You do it like this:

(from c in Context.AccountCharts 
    where c.Account_FK == account && c.Year_FK == year select c).OrderBy(order);

You have to download the System.Linq.Dynamic.dll and include it into your project.


Is there a way to order a linq query by the name of a field. like this:

from c in Context.AccountCharts 
    where c.Account_FK == account && c.Year_FK == year 
    orderby c["ColName"] select c;

Or

from c in Context.AccountCharts 
    where c.Account_FK == account && c.Year_FK == year 
    orderby c.GetType().GetField("ColName") select c;

None of these two works but I hope you know of a way to do this.


回答1:


I spend to many time to resolve this issue, but didn't find any better than:

var queryExpression;
if (c["ColName"]=="CreateDate")
    queryExpression.OrderBy(x => x.CreateDate);



回答2:


Hope this will work too though not tested

Context.AccountCharts.Where(c=>c.Account_FK == account && c.Year_FK == year).OrderBy(o=>o.order); 


来源:https://stackoverflow.com/questions/4465147/order-linq-by-string-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!