【问题标题】:Convert IEnumerable to Sum item Linq将 IEnumerable 转换为 Sum 项 Linq
【发布时间】:2021-10-08 00:29:29
【问题描述】:

我需要将 IEnumerable 转换为其他东西才能使用 Sum。我该怎么做才能做到这一点?

CsTotCommit = h.Sum(x => x.CSTotCommit)

我收到一条错误消息,指出: CapStackTrancheDTO 不包含接受 CapStackTrancheDTO 类型的第一个参数的“Sum”的定义。

        IEnumerable<CapStackTrancheDTO> debtRank = debt.AsEnumerable()
                        .Select((g,index) =>
                        new CapStackTrancheDTO
                        {
                            Rankid = index + 1,
                            CsTrancheId = g.CsTrancheId,
                            CsId = g.CsId,
                            CsTotCommit = g.CsTotCommit,
                        });


        IEnumerable<CapStackTrancheDTO> debtSum = debtRank
                      .Select(h =>
                      new
                      {
                          CsId = h.CsId,
                          CsTotCommit = h.Sum(x => x.CSTotCommit)
                      });

以下是类定义:

public class CapStackTrancheDTO
{
    public int? Rankid { get; set; }
    public int? CsTrancheId { get; set; }
    public int? CsId { get; set; }
    public decimal? CsTotCommit { get; set; }

}

我想按 CsId 和 SUM 对多条记录进行分组。

【问题讨论】:

  • 你需要把它转换成什么?
  • 我想我只是希望能够总结 CSTotCommit。我添加了我的错误消息。
  • 您需要在其中添加类定义,以便我们了解所涉及的类型。
  • 我已经添加了类定义
  • 那么在debtRank 中是否有多个CapStackTrancheDTO 实例具有相同的CsId?我正在尝试弄清楚 Sum 在这里有什么用处,因为你只有一个十进制值。

标签: c# entity-framework linq ienumerable


【解决方案1】:

在 cmets 中,您说过要按 CsId 分组,然后求和。

目前,您没有应用任何分组。

使用.GroupBy 方法,如下所示:

IEnumerable<CapStackTrancheDTO> debtSum = debtRank
    .GroupBy(h => h.CsId)
    .Select(h =>
        new CapStackTrancheDTO
        {
            CsId = h.Key, // the value we grouped on above is now available in `Key`
            CsTotCommit = h.Sum(x => x.CSTotCommit)
        }
   );

【讨论】:

  • 谢谢,这对我很有帮助!我意识到我需要 Group 才能访问 .Key。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多