Home > OS >  Convert IEnumerable to Sum item Linq
Convert IEnumerable to Sum item Linq

Time:10-10

I need to convert an IEnumerable to something else to be able to use Sum. What can I do to achieve this?

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

I receive an error stating that: CapStackTrancheDTO does not contain a definition for 'Sum' accepting a first argument of type CapStackTrancheDTO.

        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)
                      });

Here are the class defintions:

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

}

There are multiple records which I want to group by CsId and SUM.

CodePudding user response:

From the comments, you've said that you want to group by CsId and then sum.

Currently, you're not applying any grouping.

Use the .GroupBy method, like this:

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)
        }
   );
  • Related