2014-01-07 38 views
0

目標是讓一些代碼爲Where調用建立過濾條件。建設條件稍後進行過濾

在FoxPro中,我會使用構建爲字符串的條件("foo == 3 && bar > 5")並稍後執行它。

我想在C#中類似的方法 - 創建字符串,並把它作爲在下面的代碼條件,但找不到辦法做到這一點:

string Condition = ""; 

... 
if (xyz > 0) 
    Condition = "scr.ZipCode = 12345"; 

if (xyz > 1) 
    Condition = "scr.ZipCode = 23456"; 

if (xyz > 2) 
    Condition = "scr.ZipCode = 34567"; 

...etc. 

,然後在代碼中使用它:

var shippingShipCalculatorRecords = 
    _shippingShipCalculatorService.GetAllShippingShipCalculatorRecords() 
      .Where(scr => (
           (scr.CountryId == 0 && Condition) 
         ) 
      .OrderBy(x => x.Sequence).ToList(); 

我試圖將其轉換爲布爾,但它也沒有工作。我用FoxPro工作,並可以輕鬆實現它(&條件)。

+1

您無法從字符串執行代碼。相反,將郵政編碼存儲在字符串中。 – SLaks

+1

使用動態Linq? – dee

+0

看起來它實際上不是重複的(因爲Servy的回答得到了來自OP的正面反饋 - 投票重新開始)。 –

回答

7

而不是讓你的條件的字符串,有它是Expression<Func<YourEntityType, bool>>,以便您仍然可以編譯時驗證您的語法是否全部有效:

Expression<Func<YourEntityType, bool>> Condition; 

if (xyz > 0) 
    Condition = scr => scr.ZipCode == 12345; 
else if (xyz > 1) 
    Condition = scr => scr.ZipCode == 23456; 
else if (xyz > 2) 
    Condition = scr => scr.SomeOtherField == "someStringValue"; 
else 
    Condition = scr => true; //or whatever makes sense as a default choice 

var shippingShipCalculatorRecords = 
    _shippingShipCalculatorService.GetAllShippingShipCalculatorRecords() 
      .Where(scr => scr.CountryId == 0) 
      .Where(Condition) 
      .OrderBy(x => x.Sequence).ToList(); 
+1

+1。這比解析字符串更安全(因爲它是完全強類型的)。 –

+0

這似乎是解決方案。塞維正在讀我的思想,因爲我只使用ZipCode作爲表字段的樣本,但條件可以基於任何其他字段(SomeOtherField)。 – user3170203

+0

對不起,我忘了感謝你:) – user3170203

2

對不起,但AFAIK恐怕你不能這樣做。但是,你能堅持在一個變量的郵政編碼,後來在你的病情使用它:

string zipcode = string.Empty; //Or an int, if it is stored like so 

if (xyz > 0) 
    zipcode = "12345"; 

if (xyz > 1) 
    zipcode = "23456"; 

if (xyz > 2) 
    zipcode = "34567"; 

所以你的病情現在將

(scr.CountryId == 0 && src.ZipCode == zipcode) 
+2

這裏假定他添加的唯一過濾器是郵政編碼。 – Servy

+2

將zipcodes表示爲整數是有問題的,因爲前導零是非常重要的。如果使用九位郵政編碼,則會變得更糟。 –

+0

@SteveWellens那麼它取決於它如何存儲在他的側面,我不知道,但過程保持完全相同,只有聲明/分配稍微改變以適應數據類型。在我的例子中顛倒了類型,但它並不重要。 –