tags:

views:

125

answers:

2

So, I understand that group by works basically like this:

var query = from c in context.Contacts
            join o in context.Orders on c.Id on o.CustomerId
            group c by o.Id
            select new { g.Key, g.Sum(c => c.Whatever) };

Grouping like that only allows me access to the contents of c. But what if I wanted data from both tables c and o?

var query = from c in context.Contacts
            join o in context.Orders on c.Id on o.CustomerId
            //insert answer here
            select new { g.Key, g.Sum(c => c.Whatever), g.Sum(o => o.Whatever) };

Is that even possible?

+1  A: 
var query = from c in context.Contacts
            join o in context.Orders on c.Id equals o.CustomerId
            select new 
            { 
                Contact = c, 
                Order = o 
            } into ContactAndOrder
            group ContactAndOrder by ContactAndOrder.Order.Id into g
            select new 
            { 
                g.Key, 
                ContactWhatever = g.Sum(co => co.Contact.Whatever), 
                OrderWhatever = g.Sum(co => co.Order.Whatever) 
            };
Ben M
A: 

Ben's answer is a bit over-complicated, IMO. It'd be simpler to reverse the select/join pairing like this:

var query = from o in context.Orders
            join c in context.Contacts on o.CustomerId equals c.Id into Customers
            group o by o.Id into g
            select new {
                        g.Key, 
                        ContactWhatever = g.Sum(o => o.Customers.Sum(c => c.Whatever)),
                        OrderWhatever = g.Sum(o => o.Whatever)
                        };
Jacob Proffitt