2012-06-20 49 views
2

下午,我試圖做一個簡單的搜索,它是爲產品標題工作。不過,我需要在搜索中添加其他參數。我有以下代碼的基礎,至少我認爲它應該是什麼。我已經評論了其他項目簡單的LINQ搜索查詢,添加額外的參數

有人請提供一些指導,因爲我卡在它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 

非常感謝提前,所有的幫助,非常感謝。

+2

你的意思是有時你會需要額外的比較,但並非總是如此? – KingCronus

+0

是的,有些值可能爲空時,他們通過,所以我只會需要他們,如果他們不爲空:) – thatuxguy

+0

實際上所有的值可能爲空,在這種情況下,它會返回所有產品:) – thatuxguy

回答

3

我會很想做這樣的事情:

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); 
} 

等等

每次都是有條件地將過濾器,以原始查詢。

+0

我收到錯誤「查詢正文必須以select子句或group子句結尾」 – thatuxguy

+0

除了缺少選擇此項是要走的路。 –

+0

@GertArnold,我解決了這個問題,謝謝:0) – KingCronus

0

有人給我的精彩的回答:

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))); 
+0

有點想法,你可以做一整行初始querya和過濾器。但是這樣做有點快速,但它確實意味着不管你的所有過濾器如何運行在一起。 – BugFinder