[英]Dynamic change of Where filters in linq
I'm trying to do some code optimization in my app and replace several methods that do same thing with one. 我正在尝试在我的应用程序中进行一些代码优化,并用一种方法替换执行相同操作的几种方法。 I have this linq that i need to execute with various filters, but i get design time errors in .Where(filter) part 我需要使用各种过滤器执行此linq,但是在.Where(filter)部分出现设计时错误
Expression<Func<dbTable, bool>> filter;
switch (i)
{
case 1: filter = (p => p.f1 == ExternalParam);
case 2: filter = (p => p.f2 == ExternalParam);
}
var ds = (from tbl in dbEntities.dbTable
orderby tbl.f1
select new
{
f1 = tbl.f1,
f2 = tbl.f2,
f3 = tbl.f3,
f4 = tbl.f4,
}
).Where(filter);
Errors are 错误是
Error 1 'System.Linq.IQueryable<AnonymousType#1>' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource,int,bool>>)' has some invalid arguments
Error 2 Argument 2: cannot convert from 'System.Linq.Expressions.Expression<System.Func<AppNameSpace.dbTable,bool>>' to 'System.Linq.Expressions.Expression<System.Func<AnonymousType#1,int,bool>>'
Can someone help with this? 有人可以帮忙吗?
Well, your Expression is of type Expression<dbTable, bool>
好,您的表达式类型为Expression<dbTable, bool>
and you try to apply it to an anonymous
type (when you do the select new
, you're projecting to an anonymous type), which is... not a dbTable
并尝试将其应用于anonymous
类型(当执行select new
,您将投影到匿名类型),它不是... dbTable
So you should apply your predicate to an IQueryable<dbTable>
: dbEntities.dbTable
should be of that type. 因此,您应将谓词应用于IQueryable<dbTable>
: dbEntities.dbTable
应该是该类型。
var ds = from tbl in dbEntities.dbTable.Where(filter)
orderby tbl.f1
select new
{
f1 = tbl.f1,
f2 = tbl.f2,
f3 = tbl.f3,
f4 = tbl.f4,
};
By the way, I find it easier to avoid mixing syntaxes when not needed. 顺便说一下,我发现在不需要时避免混合语法会更容易。
var ds = dbEntities.dbTable.Where(filter)
.OrderBy(m => m.f1)
.Select(m => new {
tbl.f1,
tbl.f2,
tbl.f3,
tbl.f4
});
But this part is just a personal PoV. 但是,这只是个人PoV。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.