C# 如何解决双ToDouble方法给LINQ变量赋值的问题

C# 如何解决双ToDouble方法给LINQ变量赋值的问题,c#,linq-to-entities,C#,Linq To Entities,我有这行代码,它工作得很好 itemPrice = g.Sum<st_groupitem>((st_groupitem x) => x.item_price * x.item_qty) / g.Sum<st_groupitem>((st_groupitem x) => x.item_qty) 注:价格和数量等给定值为双数据类型 如何解决此问题?解决此问题的一种方法是使用Math.Round对结果进行取整,而不是尝试将其内联到LINQ中 另外,请注意,在下面的

我有这行代码,它工作得很好

itemPrice = g.Sum<st_groupitem>((st_groupitem x) => x.item_price * x.item_qty) / g.Sum<st_groupitem>((st_groupitem x) => x.item_qty)
注:价格和数量等给定值为双数据类型


如何解决此问题?

解决此问题的一种方法是使用Math.Round对结果进行取整,而不是尝试将其内联到LINQ中

另外,请注意,在下面的示例代码中,我使用了十进制而不是双精度。在处理金钱时,你应该始终使用十进制,以防止在执行数学运算时丢失精度

对原始代码行的修改如下所示:

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)
Math.Round(g.Sum((st\u组项目x)=>x.item\u价格*x.item\u数量)/g.Sum((st\u组项目x)=>x.item\u数量),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; }
}
[TestClass]
公开课轮考
{
[测试方法,测试类别(“单元”)]
public void在查找时提供两个项目,它应返回正确的值()
{
//安排
列表项=新列表
{
新项目{价格=10.123m,数量=10},
新项目{价格=20.123m,数量=20}
};
//表演
十进制实际值=数学四舍五入(items.Sum(x=>x.Price*x.Quantity)/items.Sum(x=>x.Quantity),2);
//断言
实际应为(16.79米);
}
}
公共类项目
{
公共十进制价格{get;set;}
公共整数数量{get;set;}
}

.NET框架还是核心?您使用的是哪个版本的实体框架?
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; }
}