我想在linq中使用Groupby和Left join打印Count

时间:2015-07-23 14:05:47

标签: c# linq lambda

我有两个列表或表格如下: 查询:

 var q = db.tbl_User_to_CustomerMast
     .Where(i => i.fk_Membership_ID == m.MembershipID)
     .Join(
         db.tbl_CustomerMast, 
         u => u.fk_Customer_ID, 
         c => c.CustomerID, 
         (u, c) => new { UserCustomer = u, Customer = c })
     .Where(i => i.UserCustomer.fk_Store_ID == shopid).ToList();

输出:

 List A:
    User_Customer_ID        Name
    ===================================
    1                       XYZ
    2                       ABC

查询:

var rewards = q.Join(
        db.tbl_RewardAwardMast, 
        i => i.UserCustomer.User_Customer_ID, 
        j => j.fk_Customer_UserID, 
       (i, j) => new { Customer = i, Reward = j })
   .Where(i => i.Reward.RewardDate >= i.Customer.UserCustomer.Membership_Start)
   .GroupBy(i => i.Reward.fk_Customer_UserID)
   .Select(i => new { CustomerID = i.Key, RewardCount = i.Count()})
   .ToList();

输出:

List B:
User_Customer_ID     RewardCount
===================================
1                       5

这是最终的输出表

User_Customer_ID        Name       RewardCount
===============================================
1                       XYZ            5
2                       ABC            0

如果我想检查哪个user_customer_ID少于5个奖励计数,我将如何检查:

查询:

var final = q.GroupJoin(
        rewards, 
        i => i.UserCustomer.User_Customer_ID, 
        j => j.CustomerID, 
        (i, j) => new { Customer = i, Reward = j.DefaultIfEmpty() })
    .Select(i => new { Count = i.Reward, id = i.Customer.UserCustomer.User_Customer_ID })
    .ToList();

var final1 = final.Where(i => i.Count < m.MembershipMinVisit.Value).ToList();

错误: 运营商&#39;&#39;不能应用于类型为&#39; System.Collections.Generic.IEnumerable&#39;的操作数。和&#39; int&#39;

1 个答案:

答案 0 :(得分:0)

您需要一个团体加入,因为每个客户都需要一个结果(奖励)。另外,因为您只需要有奖励的客户&lt; 5,使用该条件的内连接将为您提供所需的内容:

var final = q.Join(                               // Join instead of GroupJoin
        rewards.Where(r => r.RewardCount < 5),    // filter out rewards >= 5
        i => i.UserCustomer.User_Customer_ID, 
        j => j.CustomerID, 
       (i, j) => new { Customer = i, Reward = j })
    .Select(i => new { 
        Reward = i.Reward,                            // 'Count' is a bad name
                                                      // it is still the reward object
        id = i.Customer.UserCustomer.User_Customer_ID
    })
    .ToList();

在原始查询中,Count(错误名称)是奖励的集合(IEnumerable),这就是您收到错误的原因。要修复它,您必须检查单个返回的奖励是否为空(过滤掉没有奖励的用户,因为您使用了左连接)并且RewardCount小于5

var final1 = final.Where(i => i.Count.Single() != null &&
                              i.Count.Single().RewardCount < 5)
             .ToList();