2013-10-04 35 views
0

這裏是我的代碼:如何根據用戶輸入通過複選框更改我的查詢?

var query = from x in Data 

select new { Fruit = x[0], Animal, x[2], Color = x[3], Food = x[4] }; 

現在,我想創建複選框,以便如果用戶檢查關「框1」會做像這樣不同的查詢:

select new { Fruit = x[7], Animal, x[4], Color = x[8], Food = x[9] }; 

我的問題是,我該如何使它取決於哪個複選框被選中不同的select...new語句將被使用

我想我可以使用多個if/then語句來查看哪個特定的框被檢查並確定使用哪個select...new語句,但我猜測有更好的方法。在VB中,我認爲一個「case」語句會發揮作用,但我不知道什麼是C#等價物。

int caseSwitch = 1; 
var query = from x in Data 

switch (caseSwitch) 
{ 

     case 1: 
      select new { Fruit = x[0], Animal, x[2], Color = x[3], Food = x[4] }; 
      break; 

     case 2: 
      select new { Fruit = x[7], Animal, x[4], Color = x[8], Food = x[9] }; 
      break; 
} 
+2

的內聯LINQ的C#當量是[switch語句](http://msdn.microsoft.com/en-us/library/06tc147t(ⅴ

實施例= vs80).aspx) –

+0

好吧,我看到開關/ case ..但我如何在查詢的上下文中實現它?我試過把switch(caseSwitch){case 1:;打破; },但我認爲我沒有做對。 – phan

+1

爲什麼不把整個查詢放在switch語句中? –

回答

1

爲了改變您的查詢,您可以使用switch聲明。但是,這樣做不能使用匿名類型。您需要定義一個可以使用的對象,以便在聲明時可以定義查詢對象。

public class Foo 
{ 
    public string Fruit { get; set; } 
    public string Animal { get; set; } 
    public string Color { get; set; } 
    public string Food { get; set; } 
} 

IEnumerable<Foo> query = null; 
switch (caseSwitch) 
{ 
    case 1: 
     query = from x in Data 
       select new Foo { Fruit = x[0], Animal = x[2], Color = x[3], 
        Food = x[4] }; 
     break; 

    case 2: 
     query = from x in Data 
       select new Foo { Fruit = x[7], Animal = x[4], Color = x[8], 
        Food = x[9] }; 
     break; 

    default: 
     // handle however you need to 
} 

您也可以將它完全內聯到您的LINQ查詢中,但是,如果您爲多個案例擴展代碼將使代碼更難以理解和維護。

var query = from x in Data 
      // needed to get the caseSwitch value into context in the select 
      // otherwise it is considered out of context 
      let sw = caseSwitch 
      select sw == 1 ? 
       new { Fruit = x[0], Animal = x[2], Color = x[3], Food = x[4] } : 
       new { Fruit = x[7], Animal = x[4], Color = x[8], Food = x[9] } 

這種方法的問題是,當caseSwitch超出值的有效範圍內,你可以得到你要的不是值。通過使用switch語句可以更好地處理此問題,您可以在該語句中將查詢設置爲默認值,或在達到default大小寫時引發異常。的是如何與以上2案件

var query = from x in Data 
      let sw = caseSwitch 
      select 
       sw == 1 ? new { Fruit = x[0], Animal = x[2], Color = x[3], Food = x[4] } 
       : sw == 2 ? new { Fruit = x[7], Animal = x[4], Color = x[8], Food = x[9] } 
       : sw == 3 ? new { Fruit = x[10], Animal = x[11], Color = x[12], Food = x[13] } 
       : null; // final value is the default value 
1

你可以分解出選擇項目到一個函數:

function object getItem(DataItem x, int caseSwitch) 
{ 
    switch (caseSwitch) 
    { 
     case 1: 
      return new { Fruit = x[0], Animal, x[2], Color = x[3], Food = x[4] }; 
      break; 
     case 2: 
      return new { Fruit = x[7], Animal, x[4], Color = x[8], Food = x[9] }; 
      break; 
    } 
} 

然後你就可以做

我在不斷變化的查詢參數的情況下實現的情況下/切換失敗的嘗試以下查詢:

int caseSwitch = 1; 
var query = from x in Data 
      select getItem(x, caseSwitch);