問題描述
假設我們需要應用幾個條件來從名為事物"(未知數量和性質)的表中進行選擇
Let's say we need to apply several conditions to select from a table called "Things" (unknown count and nature)
如果條件已知,我們可以寫
if conditions are known, we can write
db.Things.Where(t=>foo1 && foo2 || foo3);
但是如果我們必須以編程方式構建 Where 條件,我可以想象我們如何應用 AND 條件
but if we have to build that Where condition programatically, I can imagine how can we apply ANDed conditions
IQuerable DesiredThings = db.Things.AsQuerable();
foreach (Condition c in AndedConditions)
DesiredThings = DesiredThings.Where(t => GenerateCondition(c,t));
ORed 條件怎么樣?注意:我們不想執行聯合、唯一或任何其他昂貴的操作,希望生成查詢就像我們臨時編寫的一樣
What about ORed conditions ? Note: we don't want to perform union, unique, or any other costly operations, it's desired that a query is generated as if we write it ad-hock
提前致謝.
PredicateBuilder: 動態組合表達式謂詞
推薦答案
您可以使用帶有靜態方法的 Expression 類來實現它的運行時.
You could use the Expression class with static methods to do it run time.
以下代碼用于創建一個委托,該委托采用一個名為 int 類型的值的參數.它從底部到頂部讀取,因此有問題的行是:
The below code is ment to create a delegate taking one argument called value of type int . It reads from buttom to top so the line in question is:
var method = LambdaExpression.Lambda(orExp, Expression.Parameter(typeof(int), "value"));
方法體將參數值與對新創建的 foo 類型對象的方法 Bar 的調用進行比較
the body of the method compares the value of the parameter to a call to method Bar of a newly created object of type foo
var exp2 = Expression.Equal(Expression.Parameter(typeof(int), "value"), Expression.Property(Expression.New(typeof(Foo).GetConstructor(new Type[] { })), "Bar"));
然后它會創建一個類似的表達式和或它們
It then creates a similar expression and or's them
var orExp = Expression.OrElse(exp1, exp2);
最后一件事是調用編譯.該調用會生成一個委托,可在您的 where 方法調用中使用.
final thing is the call to compile. That call generates a delegate that can be used in your where method call.
希望它有助于我不是 100% 確定表達式從參數中獲取值
hope it helps tho Im not 100% sure on the expression to get the value from a parameter
var exp1 = Expression.Equal(Expression.Parameter(typeof(int),"value"), Expression.Property(Expression.New(typeof(Bar).GetConstructor(new Type[] { })), "Foo"));
var exp2 = Expression.Equal(Expression.Parameter(typeof(int), "value"), Expression.Property(Expression.New(typeof(Foo).GetConstructor(new Type[] { })), "Bar"));
var orExp = Expression.OrElse(exp1, exp2);
var method = LambdaExpression.Lambda(orExp, Expression.Parameter(typeof(int), "value"));
method.Compile();
如果您需要將 LambdaExpression 轉換為不同于二進制代碼的內容(例如轉換為 SQL 語句),您可能想查看 invoke for invokation 而不是編譯表達式
You might wanna look at invoke for invokation instead of compiling the expression, if you need the LambdaExpression to be translated into something different than binary code (E.g. into an SQL statement)
這篇關于Linq2SQL“或/和"運算符(ANDed/ORed 條件)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!