Alex
Alex

Reputation: 2062

Linq query returns unwanted results as well

I'm new to linq and C#, trying to query complex objects by a certain property. The scenario is I have a list of currentPerson objects, which include PersonAddressesDisplay property, which is a string. I'm looping over the list of trying to find saved person objects in the DB by their address (PersonAddressesDisplay). Right now for some odd reason I get unwanted results as well (different strings also get in the matchAddresses list). The query is as follows:

        foreach(var currentPerson in PersonsListToSave) {
         .
         .
         .
         var matchAddresses = db.PersonAddresses.Include(p => p.Persons).AsEnumerable().
         Where(add => currentPerson.Addresses
          .Any(personAddress => personAddress.PersonAddressesDisplay == add.PersonAddressesDisplay)).ToList();
         // matchAddresses includes unwanted results
         .
         .
         .
        }

Upvotes: 0

Views: 63

Answers (1)

Zoran Horvat
Zoran Horvat

Reputation: 11301

If you want to extract PersonAddress+Person objects which share at least address with the currentPerson, then you can construct a query for that purpose directly:

foreach(var currentPerson in PersonsListToSave)
{
    // ...
    IEnumerable<string> currentAddresses = 
        currentPerson.Addresses.Select(personAddr => personAddr.PersonAddressesDisplay);

    var matchAddresses = db.PersonAddresses.Include(p => p.Persons)
        .Where(addr => currentAddresses.Contains(addr.PersonAddressesDisplay))
        .ToList();
    // ...
}

I cannot try this code, but I think that it should work correctly by constructing the WHERE - IN SQL filter under the hood. Please try it out and send more info if this is not solving the issue.

Upvotes: 1

Related Questions