[英]How to resolve issue on assigning values to LINQ variable with Double ToDouble Method
我有這行代碼運行良好
itemPrice = g.Sum<st_groupitem>((st_groupitem x) => x.item_price * x.item_qty) / g.Sum<st_groupitem>((st_groupitem x) => x.item_qty)
我想將x.item_price * x.item_qty 舍入為 2 個十進制數字。 所以我把代碼改成:
itemPrice = g.Sum<st_groupitem>((st_groupitem x) => Convert.ToDouble(String.Format("{0:0.0#}", Convert.ToDecimal(x.item_price * x.item_qty)))) / g.Sum<st_groupitem>((st_groupitem x) => x.item_qty)
但是當我運行程序時,我遇到了以下錯誤:
LINQ to Entities does not recognize the method 'Double ToDouble(System.String)' method, and this method cannot be translated into a store expression.
注意:價格和數量等給定值采用 Double 數據類型。
我該如何解決這個問題?
解決此問題的一種方法是對結果使用 Math.Round,而不是嘗試在 LINQ 中內聯它。
另外,請注意,在下面的示例代碼中,我使用了十進制而不是雙精度。 在處理金錢時,您應該始終使用小數以防止在執行數學運算時損失精度。
HTH
對原始代碼行的修改如下所示:
Math.Round(g.Sum<st_groupitem>((st_groupitem x) => x.item_price * x.item_qty) / g.Sum<st_groupitem>((st_groupitem x) => x.item_qty), 2)
而且,這是帶有測試的示例代碼:
[TestClass]
public class RoundingTest
{
[TestMethod, TestCategory("Unit")]
public void GivenTwoItems_WhenAskingToRound_ThenItShouldReturnCorrectValue()
{
// arrange
List<Item> items = new List<Item>
{
new Item { Price = 10.123m, Quantity = 10 },
new Item { Price = 20.123m, Quantity = 20 }
};
// act
decimal actual = Math.Round(items.Sum(x => x.Price * x.Quantity) / items.Sum(x => x.Quantity), 2);
// assert
actual.Should().Be(16.79m);
}
}
public class Item
{
public decimal Price { get; set; }
public int Quantity { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.