The Problem: Find all sentences with either “fox” and “dog” and “fox” or “cat”.
string[] sentences = new string[] {
"The quick brown fox jumps over the lazy dog",
"The quick brown fox jumps over the lazy cat"};
string[] findAnd = new string[] { "fox", "dog" };
string[] findOr = new string[] { "dog", "cat" };
The first part (find all) is simple:
var queryand = sentences.AsQueryable();
foreach (string find in findAnd)
{
string f = find;
queryand = queryand.Where(s => s.Contains(find));
}
Console.WriteLine(string.Join("\n", queryand.ToArray()));
But how to implement to Or part? Well, google is my best friend. I found the following solution:
Predicate Builder on C# 3.5 in a Nutshell
But this solution does not work with Entity Framework: Predicate Builder and Entity Framework on stackoverflow.com
After implementing this solution your code will look like this:
var predicate = Extensions.False<string>();
foreach (string find in findOr)
{
string f = find;
predicate = predicate.Or(s => s.Contains(f));
}
var queryor = sentences.AsQueryable().Where(predicate);
Console.WriteLine(string.Join("\n", queryor.ToArray()));
P.S.: You can find an ExpressionVisitor here: ExpressionVisitor at MSDN