Mike M Mike M - 1 year ago 67
C# Question

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

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






This data populates an
. 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.



2, 0.00, 0.00

Let's say
is a populated collection of type

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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download