2016-08-12 98 views
-3

我寫一個LINQ聲明這樣==操作符不能應用於類型爲int和字符串 - LINQ語句==

var v1 = from c in context.Orders 
     join c1 in context.Order_Details 
     on c.OrderID equals c1.OrderID 
     where c.CustomerID == 1 
     group c1 by c1.ProductID into x 
     select x; 

但它給我的錯誤

==

還有就是以下問題Comparison operators not supported for type 'System.Linq.IQueryable`1[System.Int32]' 不能應用於類型爲int和字符串的操作數,但這個問題並沒有解決我的問題

如何解決上述問題,感謝

+7

c.CustomerID的類型是什麼? –

+2

這是一個與LINQ無關的編譯器錯誤。在提出問題之前,您有責任嘗試擺脫不相關的細節。這是[最小,完整和可驗證示例]的「最小」部分(http://stackoverflow.com/help/mcve)。這是一個編譯器錯誤,如果沒有看到你的'Order'(推測)類,那麼這個錯誤是不可重現的:這就是「完整的」和「可驗證的」部分。 – hvd

回答

3

所以,我認爲c.CustomerID是一個字符串(如與ID屬性常見),而這就是問題所在。如上所述,這不是Linq問題。

話雖這麼說,要解決這個問題,只是

where c.CustomerID == "1" 

更換

where c.CustomerID == 1 

如果你有一個int變量,而不是一個常數,你可以調用toString()就可以了:

where c.CustomerID == myInt.ToString() 

雖然這不適用於雙打和浮動,所以小心!

1

該消息是自我解釋的,它清楚地表明「不能應用於int類型和字符串的操作數」。現在看進入狀態where c.CustomerID == 1這裏1是整數,c.CustomerID是字符串,以便更好地你像下面這樣:

where c.CustomerID == "1" 
0

C#是類型安全的語言,你不能用string比較的int。你的情況是比較安全的整數值轉換爲它的字符串表示:

where c.CustomerID == "1" 

您可以隨時更換,與.ToString()方法調用。

我也強烈建議你檢查你的模型,如果CustomerID是和整數,最好映射和存儲爲integer而不是string

+0

酷...!快樂的編碼 –

相關問題