-1

I have the following code that I would like to convert the for eaches into one linq statement

        decimal originalCharges = 0;
        List<int> rdns = new List<int>()
        {
            1,
            2
        };
        foreach (var customerOrder in list)
        {
            foreach (CustomerBillTo billTo in customerOrder.BillTos)
            {
                originalCharges += billTo.Charges
                    .Where(charge => rdns.Contains(charge.RateCodeRdn))
                    .Sum(charge => charge.Amount);
            }
        }

This is what I have tried so far

        originalCharges = list.ForEach(co => co.BillTos.ForEach(bt => bt.Charges.Where(charge => rdns.Contains(charge.RateCodeRdn)).Sum(charge => charge.Amount)));

Which is giving me an error cannot convert type "void" to "decimal".

I think I am getting messed up around what to do with the += for originalCharges like I did in the original forEach loops in the first example.

Can this be done in a linq statement?

originalCharges = list.ForEach(co => co.BillTos.ForEach( ));
shaun
  • 1,223
  • 1
  • 19
  • 44

1 Answers1

0

You just need to project to and flatten to the charge amounts and sum them up.

var originalCharges =
    (from customerOrder in list
    from billTo in customerOrder.BillTos
    from charge in billTo.Charges
    where rdns.Contains(charge.RateCodeRdn)
    select charge.Amount).Sum();

or if you prefer the fluent approach:

var originalCharges =
    list.SelectMany(customerOrder =>
        customerOrder.BillTos.SelectMany(billTo =>
            billTo.Charges
                .Where(charge => rdns.Contains(charge.RateCodeRdn))
                .Select(charge => charge.Amount)
        )
    ).Sum();
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272