如何在LINQ中组合多个表

时间:2009-08-06 20:58:01

标签: linq group-by

所以,据我所知,这个小组基本上是这样的:

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) };

这样的分组只允许我访问c的内容。但是,如果我想要来自表c和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) };

这甚至可能吗?

2 个答案:

答案 0 :(得分:2)

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) 
            };

答案 1 :(得分:1)

Ben的回答有点过于复杂,IMO。像这样反转选择/加入配对会更简单:

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)
                        };
相关问题