[英]Dynamic change of Where filters in linq
我正在嘗試在我的應用程序中進行一些代碼優化,並用一種方法替換執行相同操作的幾種方法。 我需要使用各種過濾器執行此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);
錯誤是
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>>'
有人可以幫忙嗎?
好,您的表達式類型為Expression<dbTable, bool>
並嘗試將其應用於anonymous
類型(當執行select new
,您將投影到匿名類型),它不是... dbTable
因此,您應將謂詞應用於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,
};
順便說一下,我發現在不需要時避免混合語法會更容易。
var ds = dbEntities.dbTable.Where(filter)
.OrderBy(m => m.f1)
.Select(m => new {
tbl.f1,
tbl.f2,
tbl.f3,
tbl.f4
});
但是,這只是個人PoV。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.