thatuxguy
thatuxguy

Reputation: 2528

simple LINQ search query, adding additional parameters

Afternoon, I am trying to make a simple search, which is working for the product title. However i need to add other parameters in for the search. I have the basis of the code below, at least what i think it should be. I have commented out the other items

Could someone please provide some guidance on this as i am stuck on it atm.

var query = from a in dc.aProducts
            join t in dc.bProducts on a.sku equals t.sku
            where SqlMethods.Like(t.title, "%" + productName + "%")

            //Compare Prices
            //&& (p => (double)p.Price >= priceFrom && (double)p.Price <= priceTo)
            //Product SKU
            //t.sku == productSku
            //Product Brand
            //t.brand == productBrand
            //a.asin == productAsin
            //a.Live == IsLive

Many thanks in advance, all help is much appreciated.

Upvotes: 2

Views: 1382

Answers (2)

KingCronus
KingCronus

Reputation: 4529

I'd be tempted to do something like this:

bool comparePrices = true;

// Join tables and get all products into query
var query = from a in dc.aProducts
            join t in dc.bProducts on a.sku equals t.sku
            select a;

// Now go through each search criteria if needed in order to filter down
if(comparePrices)
    query = query.Where(p => (double)p.Price >= priceFrom 
                          && (double)p.Price <= priceTo);

if(!string.IsNullOrEmpty(productSku))
{
    query = query.Where(t.sku == productSku);
}

Etc.

Each time you are conditionally adding filters to your original query.

Upvotes: 3

BugFinder
BugFinder

Reputation: 17868

Someone gave me the wonderful answer of:

var filters = new List<Func<f_results, bool>>();

if (comparePrices) filters.add((p => (double)p.Price >= priceFrom && (double)p.Price <= priceTo);
if (productQuery) filters.add(p => p.sku == productSku);

result = query.find (p => filters.All(filter => filter(p)));

Upvotes: -1

Related Questions