【问题标题】:LINQ Sum of prices in each month in loop?LINQ 循环中每个月的价格总和?
【发布时间】:2013-11-01 21:46:36
【问题描述】:

所以我试图从我的数据库中获取每个月的利润列表。 我想循环执行此操作,我认为这将是最好的解决方案。

这里有一个循环,我想计算每个月的利润。

        using (var context = new ModelContext("ConnectionStringDbMagazynier"))
        {
            for (int i = 0; i < 12; i++)
            {

                decimal q = (from ar in context.Archives
                             where ar.SalesDate <= DateTime.Now.AddYears(-1).AddMonths(i + 1) && ar.SalesDate >= DateTime.Now.AddYears(-1).AddMonths(i)
                             let sum = context.Archiwum.Sum(x => x.Price)
                             select sum);

                profits[i] = decimal.ToDouble(q);

            }
        }

从这个查询中我得到一个错误:

Error   2   Cannot implicitly convert type 'System.Linq.IQueryable<decimal>' to 'decimal'   

我的问题是,如何让它出现错误?这个解决方案可以吗?万一,我在特定月份没有卖任何东西并且总金额为空?

【问题讨论】:

  • 使用 .Any() 我得到“无法将类型 'bool' 隐式转换为 'decimal'”
  • 对不起。试试.Single()stackoverflow.com/questions/1544322/…
  • 更好的是,.SingleOrDefault() 所以如果当月没有销售,结果将为 0。
  • 嗨,谢谢,帮忙,我知道这会更容易,情况是我必须在 LINQ 中执行此操作,这就是任务
  • 您正在从两个表中查询,但我没有看到它们之间定义了任何协同关系。

标签: c# linq


【解决方案1】:

在这种情况下使用 lambda 语法更容易。

var q = context.Archives
    .Where(ar => ar.SalesDate <= DateTime.Now.AddYears(-1).AddMonths(i + 1) && ar.SalesDate >= DateTime.Now.AddYears(-1).AddMonths(i))
    .Sum(x => x.Price);

或者如果你真的喜欢查询语法

var records = (from ar in context.Archives
    where ar.SalesDate <= DateTime.Now.AddYears(-1).AddMonths(i + 1) && ar.SalesDate >= DateTime.Now.AddYears(-1).AddMonths(i)
    select ar);

profits[i] = records.Sum(x => x.Price);

【讨论】:

  • 我得到这个“转换为值类型 'System.Decimal' 失败,因为具体化值为 null。结果类型的泛型参数或查询必须使用可为空的类型。”
  • Price 字段可以为空吗?如果可以,请使用x =&gt; x.Price.GetValueOrDefault()
  • 不可能,但是如果我那个月什么都没卖出呢?所以mu sum什么都没有,对吧?
  • 理论上,如果您没有任何记录,Sum 应该给您零,但有时 Linq to Sql 无法实现这一点。要么在 where 子句的末尾放置一个 ToList()(对于 lambda 语法,放在 .Sum(x =&gt; x.Price) 之前的行,在查询语法中 records 的定义末尾),或者使用 Sum(x =&gt; x.Price) ?? 0。跨度>
  • x => x.Price.GetValueOrDefault() 我不能这样做,只有 GetType、CompareTo、Equals...
【解决方案2】:
var q = context.Archives
.Where(p => p.SalesDate <= DateTime.Now.AddYears(-1).AddMonths(i + 1) && p.SalesDate >= DateTime.Now.AddYears(-1).AddMonths(i))
.Sum(x => x.Price.HasValue ? x.Price.Value : 0);

可以在没有循环的情况下获取月份统计信息

  var grouped = context.Archives.Where(p=> p.SalesDate <= DateTime.Now.AddYear(-1))
.GroupBy(k => new {Year = k.Year, Month = k.Month})
.Select(p=> {Date = p.Key, Sum = p.Sum(x=> x.Price.HasValue ? x.Price.Value : 0)})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    相关资源
    最近更新 更多