我正在尝试找出一种在我的数据模型中查询对象的方法,并且只包含那些不为空的参数。如下所示:
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;
}
我已经看了几个示例,但没有真正看到任何与我需要做的事情相匹配的东西。
发布于 2010-09-21 21:50:18
您要避免的实际上是执行查询,直到您准备就绪:
public List<Widget> GetWidgets(string cond1, string cond2, string cond3)
{
MyDataContext db = new MyDataContext();
var widgets = db.Widgets;
if(cond1 != null)
widgets = widgets.Where(w => w.condition1 == cond1);
if(cond2 != null)
widgets = widgets.Where(w => w.condition2 == cond2);
if(cond3 != null)
widgets = widgets.Where(w => w.condition3 == cond3);
return widgets.ToList();
}
注意ToList
调用是如何被删除的。直到您开始迭代该查询,才会执行该查询。调用ToList
将强制执行此操作,因此可以将结果放入List<>
中并返回。我甚至建议将该方法的返回值更改为IEnumerable<Widget>
,并在最后跳过ToList
调用:
public IEnumerable<Widget> GetWidgets(string cond1, string cond2, string cond3)
{
MyDataContext db = new MyDataContext();
var widgets = db.Widgets;
if(cond1 != null)
widgets = widgets.Where(w => w.condition1 == cond1);
// [...]
return widgets;
}
这样,调用代码就可以决定何时执行查询(它甚至可以在执行查询之前添加更多条件)。
发布于 2010-09-21 22:13:21
使用“或门”:在每个小部件条件测试前面加上一个"||“,并检查我们是否使用了该条件。如果不是,则不会计算"or“的后半部分。这就是为什么它是一个门--如果第一部分的计算结果为真,我们就不再前进了。
如果是我写的,我会像下面这样写。我使用var语法糖来保存LINQ query,并将ToList()移到最后。
public List<Widget> GetWidgets(string cond1, string cond2, string cond3)
{
MyDataContext db = new MyDataContext();
var widgets = from w in db.Widgets
where (cond1 == null || w.condition1 == cond1)
&& (cond2 == null || w.condition2 == cond2)
&& (cond3 == null || w.condition3 == cond3)
select w;
return widgets.ToList();
}
编辑:语法
发布于 2010-09-21 21:55:12
像这样怎么样?
IEnumerable<Widget> condQuery = (from w in db.Widgets);
if(cond1 != null ) condQuery = condQuery.Where(w=> w.condition1 == cond1);
if(cond2 != null ) condQuery = condQuery.Where(w=> w.condition2 == cond2);
等等...?
https://stackoverflow.com/questions/3760935
复制相似问题