Linq中的分组和左连接

问题描述 投票:0回答:1

[有两个表,一个是customer的字段为customerID,GroupID,另一个是CustomerGroup的字段为GroupID,GroupName,我要获取每个组中customerID的数量,这是linq语句:

var groups = from customerGroups in db.CustomerGroup 
                         join customers in db.Customers on customerGroups.GroupID equals customers.GroupID into gc
                         where customerGroups.MerchantID == merchantID
                         from subCustomerGroups in gc.DefaultIfEmpty()
                         group customerGroups by customerGroups.GroupName into grpCustomerGroups
                         select new { GroupName = grpCustomerGroups.Key, Quantity = customers.CustomerID};

问题是Quantity = customers.CustomerID无效,如何更正该陈述?

c# linq linq-to-sql
1个回答
0
投票

实际上,您实际上需要使用Select语句对您的Group进行一些投影,然后调用Count方法,因此您需要这样的东西:

Quantity = grpCustomerGroups.Select(c => c.CustomerID).Count()

或者只是为了获得每个组的数量,您可以:

Quantity = grpCustomerGroups.Count()
© www.soinside.com 2019 - 2024. All rights reserved.