Linq表达词典 [英] Dictionary of Linq Expression
问题描述
可能重复:
在T中声明func< Out结果>动态地
我正在使用linq-to-sql来构建一个查询为了提供排序功能,我写了这样一个例子:
I'm trying to build a query using linq-to-sql and, in order to provide sorting capabilities, I wrote something like this:
private Dictionary<string, Expression<Func<DataAccess.Auditing, object>>> OrderDict { get; set; }
OrderDict = new Dictionary<string,Expression<Func<Augeos.GereonWeb.DataAccess.Auditing, object>>>();
OrderDict.Add("Date", p => (DateTime)p.RequestDateTime);
OrderDict.Add("Username", p => (string)p.CdUsername);
OrderDict.Add("Portfolio", p => (string)p.CdPortfolio);
OrderDict.Add("Url", p => (string)p.RequestedUrl);
OrderDict.Add("Result", p => (bool)p.RequestResult);
OrderDict.Add("Duration", p => (float)p.RequestDuration);
private IQueryable<DataAccess.Auditing> SetOrder(string orderBy, bool orderDirection, IQueryable<DataAccess.Auditing> query)
{
if (orderDirection)
return query.OrderByDescending(OrderDict[orderBy]);
else
return query.OrderBy(OrderDict[orderBy]);
}
我的目标是使用SortOrder函数对查询进行排序。主要的问题是Func返回一个对象,而linq不能排序这个类型的元素。我真的需要使用对象作为返回类型,因为我必须按各种类型排序。实际上是否可以稍微修改此代码并使其正常工作?
My goal is to use the SortOrder function to sort the query. The main problem is that Func returns an object and linq cannot sort elements of this type. I truly need to use object as a return type because I have to sort by a wide range of types. Is it actually possible to slightly modify this code and make it to work?
谢谢,
Gio
推荐答案
如果你在查询的表达式树中必须要非常低级才能做这样的事情。一个更简单的方法是使用DynamicLinq库,您可以在其中执行.OrderBy(),其中列为字符串值。可以找到文档这里是Scott Guthrie的博客。
Hm you'd have to go very low-level in the expression tree of your query to do such a thing. A much easier way would be to use the DynamicLinq library, where you can do .OrderBy() with a column as string value. Documentation can be found here on Scott Guthrie's blog.
这篇关于Linq表达词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!