How do I get the right fields in groups and using linq?

advertisements

I have a list of objects (Debtors) in this structure

 public class DebtorDto
    {
        public string OutstandingBalance { get; set; }
        public string Name { get; set; }
        public string Company { get; set; }
        public string InvoiceNumber { get; set; }
    }

which looks like

OUTSTANDINGBALANCE  NAME    COMPANY  INVOICENUMBER
1500                Debtor1 comp1    1235
1600                Debtor1 comp3    1236
150                 Debtor2 comp1    1234
1700                Debtor2 comp4    1237
15000               Debtor1 comp1    1238
150                 Debtor1 comp3    1239
500                 Debtor4 comp1    1274
1500                Debtor3 comp3    1634
500                 Debtor3 comp1    1334

what I would like to do is present the total amount (Sum) owed by each debtor

for example (please note the total amounts below are not accurate I've just made them up but they need to total the above amounts)

Debtor1  31050
Debtor2  3050
Debtor3  1050
Debtor4  41050

what I have so far is

var query = from e in _allDebtors.GroupBy(x => x.Company)
                .Select(y => y.Sum(z => decimal.Parse(z.OutstandingBalance))))))

this actually gives me the correct amounts like below but I don't know how to get the name of the debtor in there as well?

31050
3050
1050
41050


You need to change your return value in the Select:

var query = _allDebtors.GroupBy(x => x.Company)
            .Select(y => new { Company=y.Key, Total=y.Sum(z => decimal.Parse(z.OutstandingBalance)) });

Note that this is by company - if you want it by debtor, it would be:

var query = _allDebtors.GroupBy(x => x.Name)
            .Select(y => new { Name=y.Key, Total=y.Sum(z => decimal.Parse(z.OutstandingBalance)) });