2014-09-02 128 views
1

使用lambda,我想更換根據這些條件的數據表列item_typeitem_status的值:替換列值

  • ITEM_TYPE =「A」,則與「蘋果」
  • 替換
  • ITEM_TYPE = 「B」 與 「香蕉」 更換
  • 否則顯示原始數據
  • ITEM_STATUS = 「A」,則與 「蘋果」
  • ITEM_STATUS = 「B」 repla取代用 「香蕉」 CE
  • 否則顯示原始數據

command.CommandText = "select [item no], item_type, item_status from dbo.GetItems()"; 
command.CommandType = CommandType.Text; 
da.SelectCommand = command; 
da.Fill(dt); 

dgItems.DataSource = dt; 

我想是這樣的:

dgItems.DataSource = dt.Select(...); 
+1

什麼樣的數據源產生'da.Fill'? (它是一個類型化的數據集)?這對你自己來說更容易(擁有智能感知)。而且,如果你想改變結果,我會**不**使用LINQ(這是一個反模式) - 使用'foreach'並在它內部進行變異 – Carsten 2014-09-02 06:01:02

+0

是的。對於所有場景,您可以更改您的'SQL'或在DataTable行上使用'foreach'循環一次。 – Hassan 2014-09-02 06:05:39

+0

我想說,你試圖以錯誤的方式做這個totaly,這樣的轉換應該在數據庫方面作爲額外的列中的顯示值而不是在代碼中的某處通常完成。 – 2014-09-02 06:11:01

回答

0

我同意你的SQL代碼這樣做是爲了獲得所需的如果可能的話,數據首先是最好的選擇。

要回答這個問題,就好像問:

Array.ForEach(dt.Rows.Cast<DataRow>().ToArray(), 
       row => 
       { 
        if (row.Field<string>("item_type") == "A") 
         row.SetField("item_type", "Apple"); 
        else if (row.Field<string>("item_type") == "B") 
         row.SetField("item_type", "Banana"); 

        if (row.Field<string>("item_status") == "A") 
         row.SetField("item_status", "Apple"); 
        else if (row.Field<string>("item_type") == "B") 
         row.SetField("item_status", "Banana"); 
       }); 

那將修改原始DataTable