ef core group by 去生重

ef  core group by 去生重复,保留指定条件行

 //当前活动信息
            var actQry = from ap in _activityProductRep.DetachedEntities
                         join a in _activityRep.DetachedEntities on ap.ActivityId equals a.Id into aTemp
                         from act in aTemp.DefaultIfEmpty()
                         where act != null
                         select new ActivityProductCom
                         {
                             ActivityId = act.Id,
                             Title = act.Title,
                             Weight = act.Weight,
                             StartTime = act.StartTime,
                             EndTime = act.EndTime,
                             ActRuleType = act.ActRuleType,
                             ProductId = ap.ProductId,
                             Price = ap.Price,
                             Text = ap.Text,
                             Amount = ap.Amount,
                             ActivityProductId = ap.Id
                         };


            //按权重过滤,保存权重最大的那权记录
            var actQry1 = from ap in actQry
                          group ap by ap.ProductId into g
                          select new// 这里必须重新new一个结果,不能直接 select g.OrderByDescending(x => x.Weight).FirstOrDefault()
                          {
                              // g.OrderByDescending(x => x.Weight).FirstOrDefault()相当于一个子查询,只能为了性能只使用一个字段ActivityProductId
                              ActivityProductId = g.OrderByDescending(x => x.Weight).FirstOrDefault().ActivityProductId,
                          };
            //过滤重复
            actQry = actQry.Where(x => actQry1.Any(w => w.ActivityProductId == x.ActivityProductId));

 

posted @ 2022-07-19 16:11  evemen  阅读(261)  评论(0编辑  收藏  举报