我試圖找出一種方法來查詢我的數據模型中的一個對象,並且只包含那些非空的參數。如下圖所示:在LINQ查詢中執行條件'if'語句'where'語句
public List<Widget> GetWidgets(string cond1, string cond2, string cond3)
{
MyDataContext db = new MyDataContext();
List<Widget> widgets = (from w in db.Widgets
where
... if cond1 != null w.condition1 == cond1 ...
... if cond2 != null w.condition2 == cond2 ...
... if cond3 != null w.condition3 == cond3 ...
select w).ToList();
return widgets;
}
由於部件表可以得到非常大的,我想避免這樣做:
public List<Widget> GetWidgets(string cond1, string cond2, string cond3)
{
MyDataContext db = new MyDataContext();
List<Widget> widgets = db.Widgets.ToList();
if(cond1 != null)
widgets = widgets.Where(w => w.condition1 == cond1).ToList();
if(cond2 != null)
widgets = widgets.Where(w => w.condition2 == cond2).ToList();
if(cond3 != null)
widgets = widgets.Where(w => w.condition3 == cond3).ToList();
return widgets;
}
我看了幾個例子,但沒有真正看到任何匹配我需要做的事情。
是否由JIT編譯器在結果查詢中刪除條件?或者linq'保證'一些優化? – xtofl 2010-09-21 16:51:43
@xtofl:不確定你的意思?你想擺脫哪些條件? – 2010-09-21 17:49:02
如果條件不滿足,它們不會添加到表達式樹中。 – Michael 2010-09-22 02:02:43