Mike M Mike M - 2 months ago 13
C# Question

C# LINQ: Projecting a detail object into a summary object

I have a .csv and the data looks like so:

Account,Debit,Credit

1,10.00,5.00

1,10.00,10.00

2,5.00,5.00

2,10.00,10.00


This data populates an
IEnumerable<Source>
. The definition is below:

public class Detail {

public string Account {get; set;}
public decimal Debit {get; set;}
public decimal Credit {get; set;}

}


I am attempting to consolidate and project this "detail" object into a summarized object where Total is the sum of debits and credits per account.

public class Summary {

public string Account {get; set;}
public decimal Total {get; set;}

}


The end result I'm shooting for is a distinct list of accounts which have all debits and credits rolled up per account, so that instead of multiple lines per account/debit/credit, I have a summary projection.

Account,Debit,Credit


1,5.00,0.00

2, 0.00, 0.00


Let's say
detailrecords
is a populated collection of type
IEnumerable<Detail>
.

var results = detailrecords
.GroupBy(x => x.Account)
.Select(c => new Summary() {
Account = ?? I can't figure out how to access my detail properties here
Total = ?? I am not sure how to perform arithmetic without access to detail properties
}).ToList();

Answer

What you are looking for is something like this:

var results = detailRecords
        .GroupBy(x => x.Account)
        .Select(c => new Summary
        {
            Account = c.Key,
            Total = c.Sum(y => y.Credit + y.Debit)
        }).ToList();
Comments