Matching on search attributes selected by customer on front end

Posted by CodeNinja1974 on Stack Overflow See other posts from Stack Overflow or by CodeNinja1974
Published on 2012-11-11T08:42:47Z Indexed on 2012/11/11 11:01 UTC
Read the original article Hit count: 193

Filed under:
|

I have a method in a class that allows me to return results based on a certain set of Customer specified criteria. The method matches what the Customer specifies on the front end with each item in a collection that comes from the database. In cases where the customer does not specify any of the attributes, the ID of the attibute is passed into the method being equal to 0 (The database has an identity on all tables that is seeded at 1 and is incremental). In this case that attribute should be ignored, for example if the Customer does not specify the Location then customerSearchCriteria.LocationID = 0 coming into the method. The matching would then match on the other attributes and return all Locations matching the other attibutes, example below:

public IEnumerable<Pet> FindPetsMatchingCustomerCriteria(CustomerPetSearchCriteria customerSearchCriteria)
{   
    if(customerSearchCriteria.LocationID == 0)
    {         
         return repository.GetAllPetsLinkedCriteria()
                     .Where(x => x.TypeID == customerSearchCriteria.TypeID &&
                                 x.FeedingMethodID == customerSearchCriteria.FeedingMethodID &&
                                 x.FlyAblityID == customerSearchCriteria.FlyAblityID )
                     .Select(y => y.Pet);
    }
}

The code for when all criteria is specified is shown below:

private PetsRepository repository = new PetsRepository();

public IEnumerable<Pet> FindPetsMatchingCustomerCriteria(CustomerPetSearchCriteria customerSearchCriteria)
{            
    return repository.GetAllPetsLinkedCriteria()
                     .Where(x => x.TypeID == customerSearchCriteria.TypeID &&
                                 x.FeedingMethodID == customerSearchCriteria.FeedingMethodID &&
                                 x.FlyAblityID == customerSearchCriteria.FlyAblityID &&
                                 x.LocationID == customerSearchCriteria.LocationID )
                     .Select(y => y.Pet);
}

I want to avoid having a whole set of if and else statements to cater for each time the Customer does not explicitly select an attribute of the results they are looking for. What is the most succint and efficient way in which I could achieve this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ