gpt4 book ai didi

c# - LINQ with Entity Framework,获取计算总和

转载 作者:行者123 更新时间:2023-12-02 22:31:37 25 4
gpt4 key购买 nike

我有以下数据:

enter image description here

数字可以为NULL

我正在编写 LINQ 语句以获取以下数字作为结果:

  • 100 乘以 110 是 110
  • 200 乘以 90 是 180

需要的结果:290

我的 LINQ 语句目前如下所示:

(from b in data
where b.Number.HasValue
select new
{
Number = b.Number.Value,
b.Factor
}).Sum(o => o.Number * (o.Factor / 100));

我收到以下错误:

The cast to value type 'Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

最佳答案

这可以通过像这样转换 Sum 的内容来解决:

(from b in data
where b.Number.HasValue
select new
{
Number = b.Number.Value,
b.Factor
}).Sum(o => (decimal?)(o.Number * ((decimal)o.Factor / 100))) ?? 0;

(注:我在写问题的时候找到了答案,我想我不妨制定一个答案并发布给其他人找到)

关于c# - LINQ with Entity Framework,获取计算总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12142659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com