views:

900

answers:

3

Duplicate:

http://stackoverflow.com/questions/782339/how-to-dynamically-add-or-operator-to-where-clause-in-linq

I want to loop through a array of string values and build a linq expression

Where each item in the list is OR'ed together.

string[] search = new string[]{"A", "B", "C"};
foreach (string item in filterValues)
{
    searchQuery = searchQuery.Where(s => s.Name.Contains(item));
}

The code above searched for "A" AND "B" AND "C"

I want to search for "A" OR "B" OR "C".

I know how to do this with Linq but I want to accomplish the same thing using extension methods.

A: 

It's not a duplicate. Yes it exposes that deferred execution problem which the other post is about but his question relates to being able to call Where and have it append as an OR and not an AND. I too would like to know if this is possible.

+1  A: 
var filterValues = new[] { "A", "B", "C" };

var values =
    (from item in filterValues
     from value in searchQuery
     where value.Name.Contains(item)
     select value)
     .Distinct();
Joe Chung
A: 

I struggled with this today. Then I finally realized that if I made the array into a List of Strings I could do a join. A queryextender control (.NET 4) is calling the function below. Dont forget the order by... its important. you'll get an error if you don't use it.

    Protected Sub FilterTestType(ByVal sender As Object, ByVal e As CustomExpressionEventArgs)
    Dim _codes As List(Of String) = GetTestCodes()
    e.Query = From _tests In e.Query.Cast(Of LabTest)()
              Join _code In _codes On _tests.TestCode Equals _code
              Order By _tests.LoadDate Descending
              Select _tests
End Sub
Dan