Linq Group By Into with附加参数

时间:2016-08-23 11:23:07

标签: c# asp.net-mvc linq

我有以下sql结果: 表结果

enter image description here

目标是通过ProjectId和SequenceId对此结果进行分组。后面的JSON结果应如下所示:

[
  {
    "ProjectId": 1,
    "ProjectName": "Testprojekt 1",
    "Sequences": [
      { 
        "SequenceId": 2,
        "SequenceName": "ESN_Tauschen" 
      },
      {
        "SequenceId": 3,
        "SequenceName": "Demontage"
      }
    ]
  },
  {
    "ProjectId": 2,
    "ProjectName": "Testprojekt 2",
    "Sequences": [
      {
        "SequenceId": 3,
        "SequenceName": "Demontage"
      }
    ]
  }
]

我当前的linq表达式给出了以下结果:

[
  {
    "ProjectId": 1,
    "Sequences": [
      2,
      3
    ]
  },
  {
    "ProjectId": 2,
    "Sequences": [
      3
    ]
  }
]

 var context = new ReworkPlace();

        var result = from p in context.Projects
                     join rs in context.ReworkStations on p.ProjectId equals rs.ProjectId
                     join l in context.ReworkStationReworkConfigurationLinkSets on rs.ReworkStationId equals
                         l.ReworkStationId
                     join rc in context.ReworkConfigurations on l.ReworkConfigurationId equals rc.ReworkConfigurationId
                     join s in context.Sequences on rc.SequenceId equals s.SequenceId
                     group s.SequenceId by p.ProjectId into g
                     select new
                     {
                         ProjectId = g.Key,
                         Sequences = g.ToList()
                     };


        return Json(result, JsonRequestBehavior.AllowGet);

我不知道如何调整我的linq表达式以将未分组的属性(如ProjectName,SequenceId和SequenceName)包含到我的json结果中。

如果有人可以帮助我会很好。

1 个答案:

答案 0 :(得分:1)

要在不完全重写查询的情况下获得所需结果,请替换分组部分:

 group s.SequenceId by p.ProjectId into g
 select new
 {
     ProjectId = g.Key,
     Sequences = g.ToList()
 };

有这样的事情:

group new { p, s } by p.ProjectId into g
let p = g.FirstOrDefault().p
select new
{
    ProjectId = g.Key,
    ProjectName = p.Name,
    Sequences =
        (from e in g
         group e.s by e.s.SequenceId into g2
         let s = g2.FirstOrDefault()
         select new
         {
             SequenceId = g2.Key,
             SequenceName = s.Name
         }).ToList()
};

诀窍是在groupby之间包含分组内部所需的数据(除Key之外的by之后FirstOrDefault )。

要获取其他字段,您可以将它们包含在分组键中,或者如果它们对于定义的分组键是相同的,请使用RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([\w-]+)/([\w-]+)/?$ company.php?company=$1&staff=$2 [L,QSA] RewriteRule ^c/([\w-]+)/?$ company.php?company=$1 [L,QSA,NC] 从分组中的第一条记录中获取它们,如同上面的例子。