Apologies for the terrible title, I wasn't quite sure how to phrase my problem.
I have an object that looks like:
CustAcct cust = new CustAcct();
cust.Name = "John Doe";
cust.Account = "ABC123";
cust.OrderTotal = 123.43
cust.OrderQty = 4;
cust.TransDate = "12/26/2010 13:00"
Please don't spend too much time criticizing the next part because this really doesn't deal with a shopping cart/Customer stuff but the idea is the same, I just wanted to use something that everyone is pretty familiar with.
An account can have more than one customer, and a customer can have more than one account.
So you have:
List<CustAcct> custList = new List<CustAcct>();
custList.Add("John Doe", "ABC123", 123.43, 4, "12/26/2010 13:00");
custList.Add("John Doe", "ABC123", 32.12, 2, "12/27/2010 10:00");
custList.Add("John Doe", "ABC321", 43.34, 1, "12/28/2010 15:00");
custList.Add("John Doe", "ABC321", 54.60, 3, "12/28/2010 16:00");
custList.Add("Jane Zoe", "ABC123", 46.45, 2, "12/28/2010 17:00");
custList.Add("Jane Zoe", "ABC123", 32.65, 1, "12/29/2010 12:00");
custList.Add("Jane Zoe", "ABC321", 67.65, 3, "12/29/2010 23:00");
custList.Add("Jane Zoe", "ABC321", 75.34, 4, "12/30/2010 08:00");
What I would like to do is get the sum of all OrderTotal and OrderQty for each Account and Customer so my output will look like:
Account    Customer    OrderTotal    OrderQty
 ABC123     John Doe    155.55          6
 ABC321     John Doe     97.94          4
 ABC123     Jane Zoe     79.10          3
 ABC321     Jane Zoe    142.99          7
I've been through my LINQ to Objects book and 101 LINQ Samples and can't figure out how to go about getting this. Thanks.
You can group and sum like this:
from ca in custList
group ca by new { ca.Name, ca.Account } into g
select new {
    g.Key.Account,
    g.Key.Name,
    OrderTotal = g.Sum(o => o.OrderTotal),
    OrderQty = g.Sum(o => o.OrderQty)
};
See it in action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With