Resharper says to convert foreach to LINQ, but is it possible?

I have a Project entity that has a navigational property which is a list of Addresses. On a search page I allow the user to search for projects by several addresses at a time. Is it possible to do this in a single statement or do I need to loop though the searched addresses?

Currently I have the following code where searchedAddresses is a list of addresses used to search for a project. In the foreach loop, I create a query and union it with the overall query each time through the loop. Resharper is saying the foreach can be rewritten using LINQ and I'd like to get rid of the unioning of queries if possible.

foreach (AddressModel address in searchedAddresses)
{
    var query = _projectRepository.Get().Where(p => p.Addresses.Any(a => a.StreetName.ToLower().StartsWith(address.StreetName.ToLower())));

    union = (union == null ? query : union.Union(query));
}

I've tried to write it as one statement, but it does not work:

var query = _projectRepository.Get().Where(p => p.Addresses.Any(a => searchedAddresses.Any(sa => a.StreetName.ToLower().StartsWith(sa.StreetName.ToLower())));

When doing this I get the following error: "Unable to create a constant value of type 'EPIC.WebAPI.Models.AddressModel'. Only primitive types or enumeration types are supported in this context."

I'm assuming this is because of the searchedAddresses.Any() part. Does anyone know how to write this query so that I don't need to loop through the addresses and union the queries? Or is this an OK thing to do?

Thanks!

EDIT: Added the ToLower and StartsWith to the second query which I initially forgot.

Jon Skeet
people
quotationmark

I suspect the simplest approach is to create a List<string> for the street names you're searching for first - I would expect those to be convertible:

var searchedStreets = searchedAddresses.Select(x => x.StreetName).ToList();
var query = projectRepository
      .Get()
      .Where(p => p.Addresses.Any(a => searchStreets.Contains(a.StreetName)));

If a List<string> doesn't work, it's probably worth trying a string[]. (Just change ToList to ToArray.)

people

See more on this question at Stackoverflow