【问题标题】:group by in linq doesn't show the expected resultlinq 中的 group by 未显示预期结果
【发布时间】:2016-08-13 12:50:41
【问题描述】:

我有这些表:

TestPackagejoint(id,testpackageid,jointid)
Joint(id,endid)

我在testpackagejoint 和基于jointid,id 的关节之间创建了一个联合。

我想根据endidtestpackageidendid 的计数或示例对值进行分组:

testpackageid       endid       count
1                     2          3
4                     2          1
1                     3          2 

所以我写了这个查询

 var q = (from i in _ctx.TestPackageJoints
                where i.TestPackageId == Id
                join joint1 in _ctx.Joints on i.JointId equals joint1.Id
                group new {joint1.EndId,i.TestPackageId} by new { i, joint1}
                into g1
                select new
                {
                    testpackid = g1.Key.i.TestPackageId,
                    Count = g1.Count(),
                    endid = g1.Key.joint1.EndId
                }).ToList();

但是结果:

【问题讨论】:

    标签: c# linq group-by


    【解决方案1】:

    你必须明白想要得到什么。你想得到testpackid和endid,所以把它们分组是正确的。你还想按 testpackid 和 endid 分组,为什么在这里按 new {i, ...} 分组。

    试试

    group new {joint1.EndId,i.TestPackageId} by new {joint1.EndId,i.TestPackageId}
    

    或者

    join ...
    let item = new {joint1.EndId,i.TestPackageId}
    group item by item
    

    【讨论】:

      【解决方案2】:

      您的查询应该是:

      var query =
          from tpj in _ctx.TestPackageJoints
          join j in _ctx.Joints on tpj.JointId equals j.Id
          where tpj.TestPackageId == id
          group 1 by new { tpj.TestPackageId, j.EndId } into g
          select new
          {
              g.Key.TestPackageId,
              g.Key.EndId,
              Count = g.Count(),
          };
      

      group by 子句的格式为group [object] by [key]。您包含一个 TestPackageJoint 对象作为键的一部分,它可能没有定义相等性,因此它为每个配对生成一个组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多