Search code examples
c#.netlinqentity-frameworklinq-to-entities

How to do a simple OR query with LINQ?


I am using LINQ to Entities and I'm trying to do a simple OR query. I have a table called "Links" and when I run a query I want to include all links containing any tag from a list of tags and all links matching a search term. For example:

var tags = new List<string>
{
    "games",
    "events",
    "recipes"
};

var searchTerms = new List<string>
{
    "hockey",
    "barbecue",
    "cheesecake",
    "basketball"
}

var links = _entityContainer.Links
    .Where(x => x.Tags.Any(y => tags.Contains(y.Name))
    .Where(x => searchTerms.Any(y => x.Title.Contains(y)));

Note: a link entity has a navigation property called Tags so in the first .Where() I'm checking each of the tags in the link's collection to see if the list of tags I'm searching for contains one of them.

In the second .Where() I'm simply checking if the link's Title property contains any of the search terms.

My problem is that this code includes all links that contain at least one tag from the list AND match one of the search terms. But I want to include both together. I want my links list to include all links that either match 1 or more tags in the list OR match 1 or more search terms in the list.

I also have an issue because of tags.Contains() and searchTerms.Any() because these are calls that cannot be converted into expressions to be passed to EF. They would work if I did ToList() but I cannot do that as it would pull a very large number of records into memory.

Any suggestions for accomplishing my goal?


Solution

  • Condense it to one Where clause:

    var links = _entityContainer.Links
        .Where(x => 
            x.Tags.Any(y => tags.Contains(y.Name)) ||
            searchTerms.Any(y => x.Title.Contains(y)));