2011-09-29 57 views
3

我有這個錯誤,我打算解決。運算符' - '不能應用於類型'decimal'和'Systems.Collections.Generic.IEnumerable的操作數<decimal>

Visual Studio 2010中提供了錯誤爲:

operator '-' cannot be applied to operands of type 'decimal' and 'Systems.Collections.Generic.IEnumerable<decimal> 

我的代碼:

// Step 5: Retrieve MPR amount and deduct form Gross Tax Dictionary Per-Employee 

       //Query database 
       var taxtable = taxTableService.GetAllTaxTables(); 

       var mprAmount = (from tt in taxtable select tt.U_MPR_amount).Distinct(); 

       Dictionary<int, decimal> paye = new Dictionary<int, decimal>(); 

       grossTaxDictionary.ToList().ForEach(x => 
       { 
        var totalPAYE = x.Value - mprAmount; 

        paye.Add(x.Key, totalPAYE); 

       }); 

在我的數據庫,場U_MPR_amount是一個小數,所以是x.Value。

錯誤顯示出來就行了x.Value - mprAmount;

可能是什麼問題呢?任何幫助讚賞。

回答

7

根據你的代碼,mprAmount是一個列表,你不能從一個值中減去它。

var totalPAYE = x.Value - mprAmount.Single(); 

或者,更有可能:

var mprAmount = (from tt in taxtable select tt.U_MPR_amount).Single(); 

注意到我

如果您確定該列表包含只是一個單一的元素,那麼你可以使用Single方法檢索Distinct更改爲Single。使用兩者都沒有意義。

+0

我認爲Single比First更合適,因爲如果mprAmount具有多個單值,它會暴露OPs假設中的任何缺陷。 – spender

+0

@spender Yup,完全正確。也就是說,很可能多個值實際上都很好,在這種情況下,只有第一個值是必要的,或者可能有多個相同的值(其中'Distinct'會很小心)。在這兩種情況下,'First * *'都可能適用。 –

+0

啊,我明白了。稅表一次只能存儲一條記錄,並沒有使用單個記錄。非常感謝Konrad。解決了。 –

相關問題