我有一个这样的对象:基于空参数Linq查询建设
public class Filters
{
List<string> A { get; set; }
List<string> B { get; set; }
}
我将用它作为将在数据库执行查询的功能参数。 这些itens,A和B将指示“where”过滤器。
请看下面的代码:
//Filters Initialization
Filters TestFilters = new Filters();
TestFilters.A = new List<string>();
TestFilters.B = new List<string>(new string[] {"testfilter1","testfilter2"}); //WHERE B == "testfilter1" OR B == "testfilter2"
//Call of the function that executes SELECT on DB
List<Table> Result = TestFunction(TestFilter);
功能:
public static List<Table> TestFunction(Filters pParameter)
{
ExampleDataContext dc = new ExampleDataContext(Properties.Settings.Default.ExampleConnectionString);
List<Table> SelectResult = new List<Table>();
if (pParameter.A.count != 0 && pParameter.B.count != 0)
SelectResult = (from x in dc.Table
where pParameter.A.Contains(x.A)
where pParameter.B.Contains(x.B)
select x).ToList();
else if (pParameter.A.count == 0 && pParameter.B.count != 0)
{
SelectResult = (from x in dc.Table
where pParameter.B.Contains(x.B)
select x).ToList();
}
else if (pParameter.A.count != 0 && pParameter.B.count == 0)
{
SelectResult = (from x in dc.Table
where pParameter.A.Contains(x.A)
select x).ToList();
}
else if (pParameter.A.count == 0 && pParameter.B.count == 0)
{
SelectResult = (from x in dc.Table
select x).ToList();
}
return SelectResult;
}
有时A或/和B是/都是空的,那么我使用 “IF” 结构来处理它。 也许我可能会遇到一个问题,即我的过滤器更大,超过2个参数,编码会很困难/无聊。 我的问题是:它正在工作,但有没有另一种方式来做到这一点,而不是使用IF?
你应该使用链式LINQ查询,这是与新的查询继续旧的查询结果。你不应该每次都在x上查询。 –