I’m trying to create a class that allow me to configure LINQ query at run time by using .Where() method, after completing my class and while testing result was not as I expected so I had an issue and to resolve that I needed to call multiple .Where() method times and it should act like OR || not like AND &&
Example:
class Program
{
private static string WhereTest()
{
string result = "";
// List
string[] lst = { "Sa", "Su", "Mo", "Tu", "We", "Th", "Fr" };
// test 1
var q1 = from l in lst
where l.StartsWith("S") && l.EndsWith("u")
select l;
result = "1st query count: " + q1.Count()
+ "\n----------------- \nItems: \n------- \n";
foreach (var item in q1.ToList())
{
result += item + "\n";
}
result += "\n";
result += "\n";
// test 2
var q2 = from l in lst
where l.StartsWith("S") || l.EndsWith("u")
select l;
result += "2nd query count: " + q2.Count()
+ "\n----------------- \nItems: \n------- \n";
foreach (var item in q2.ToList())
{
result += item + "\n";
}
result += "\n";
result += "\n";
// test 3
var q3 = from l in lst
select l;
if (true)
q3 = q3.Where(l => l.StartsWith("S"));
if (true)
q3 = q3.Where(l => l.EndsWith("u"));
result += "3rd query count: " + q3.Count()
+ "\n----------------- \nItems: \n------- \n";
foreach (var item in q3.ToList())
{
result += item + "\n";
}
result += "\n";
result += "\n";
return result;
}
static void Main(string[] args)
{
Console.WriteLine(WhereTest());
}
}
Result:
1st query count: 1
-----------------
Items:
-------
Su
2nd query count: 3
-----------------
Items:
-------
Sa
Su
Tu
3rd query count: 1
-----------------
Items:
-------
Su
In my example q3 return the same result of q1
So I need to know if I can make q3 return me the same reult of q2.
Regards
For LINQ to SQL or other queryable-based providers,
PredicateBuilderis the solution. It doesn’t let you callWheremultiple times, but it lets you create a predicate dynamically using multiple calls.For LINQ to Objects, you can create your own equivalent of
PredicateBuilderusing delegates instead of expression trees, as shown in this answer. Just to make this answer complete in its own right, here’s the same code again:So you’d use something like: