找到最高总和值并取3

时间:2013-02-05 22:41:24

标签: c# .net linq nhibernate

我有这段代码(不确定它是否有效,因为我无法测试它):

var test = base.UnitOfWork.Session.Query<NutritionFact>()
                                  .Where(x => x.NutritionalServing.Id == servingId)
                                  .GroupBy(x => x.UserVerifiedFacts)
                                  .OrderByDescending(x => x.Sum(e => e.UserVerifiedFacts.Count()))
                                  .Take(3)
                                  .Select(r => new
                                      {
                                          c = r.Key,
                                          Sum = r.Sum(x => x.UserVerifiedFacts.Count())
                                      })
                                  .ToList();

我要做的是查找具有正确NutritionFacts的所有servingId。然后,我想要计算每个NutritionFacts找到的用户数已经验证信息的数量。然后我想得到前3个结果并使用它们。

我现在正在做的是导致“未实现”的错误,这显然是因为nhibernate sum只能处理没有参数。

enter image description here

1 个答案:

答案 0 :(得分:2)

我会尝试:

var test = ...Query<NutritionFact>()
             .Where(x => x.NutritionalServing.Id == servingId)
             .Select(x=> new { Nf= x, VfCount= x.UserVerifiedFacts.Count() })
             .OrderByDescending(x => x.VfCount))
             .Take(3)
             .ToList();

您无需使用SumSum用于汇总(汇总)分组列,但您只想Count()每个特定NuturitionFact相关表格中的行数。

它对应于这个SQL语句(我想,你需要的是什么)

SELECT TOP 3 n.*, 
       (SELECT COUNT(*) FROM UserVerifiedFact uv WHERE uv.NuturitionFacts_Id = n.Id) AS NumbOfVer  
       FROM NutritionFact n 
       WHERE n.NutritionalServing_Id = @servingId
       ORDER BY NumbOfVer DESC