如何使分组linq查询像平面表

时间:2011-02-24 17:46:42

标签: linq

您好 我想为表创建一个查询,如下所示: 1.i有一个多个问题,我想计算每个答案对多个问题结果的响应次数,并在一个如下格式的查询中显示它们: 1.ID 2.qestion短语3.q1 4.q2 5.q3 6.q4 7.count1 8.count2 9.count3 10.count4 我已经创建了一个这样的linq查询,它来自于答案表,之后我可以将这些与ID一起加入问题表并获得短语和其他:

var q4 = (from x in LinqDB.PTAs
             where x.PTID == int.Parse(DropDownListPeriodID.SelectedValue) &&
                   x.PTUser.PTUserID >= ID1 && x.PTUser.PTUserID <= ID2 
             group x by x.PTQID into GRPA //& x.PTAID
             select new {
                 GRPA.Key,
                 A1=(
                     from f in GRPA
                     group f by f.Answer into FG
                     select FG.Count()
                    )});

但它提供了第二层,我不想要这种格式  我试过这个:

var Q = from x in LinqDB.PTAs
            where x.PTID == int.Parse(DropDownListPeriodID.SelectedValue) &&
                  x.PTUser.PTUserID >= ID1 && x.PTUser.PTUserID <= ID2 
            group x by new { x.PTQID, x.Answer } into gr
            select new {gr.Key.PTQID,gr.Key.Answer,A1=gr.Count() };

所以对此有任何建议或者可能在后期处理中更改第二个查询,以便它可以像我的格式一样? 谢谢你的答案。

1 个答案:

答案 0 :(得分:0)

  //process user input before going into the database.
int selectedID = int.Parse(DropDownListPeriodID.SelectedValue);

  //go to the database and get the data.
List<PTA> records =
(
  from x in LinqDB.PTAs
  where x.PTID == selectedID
    && ID1 <= x.PTUser.PTUserID && x.PTUser.PTUserID <= ID2
  select x
).ToList();

 // group up the data for presentation.    
var questions =
  from x in records
  group x by new {x.PTQID, x.Answer} into g1
  group g1 by g1.Key.PTQID into g2
  select new
  {
    PTQID = g2.Key,
    Answers =
       from y in g2
       select new
       {
         Answer = y.Key.Answer,
         AnswerCount = y.Count()
       }
  };

    // group up the data for presentation.
   var questions =
   from x in records
   group x by x.PTQID into g
   let answers = g.GroupBy(y => y.Answer)
   let answer1 = answers.First()
   let answer2 = answers.Skip(1).First()
   let answer3 = answers.Skip(2).First()
   let answer4 = answers.Skip(3).First()
   select new
   {
     PTQID = g.Key,
     Answer1 = answer1.Key,
     Answer1Count = answer1.Count(),
     Answer2 = answer1.Key,
     Answer2Count = answer1.Count(),
     Answer3 = answer1.Key,
     Answer3Count = answer1.Count(),
     Answer4 = answer1.Key,
     Answer4Count = answer1.Count(),
   };