Linq返回的子数组不正确

时间:2013-09-09 08:15:21

标签: c# linq jqgrid

为jqGrid准备数据我得到了一个意外的子网格单元格数组。简化的代码如下所示:

var result = new
{
    total = 1,
    page = 1,
    records = qstList.Count(),
    rows =  qstList.Select(( c, i ) => new
            {
                Id = c.QuestionId,
                Text = c.Text,
                Type = c.Type,
                Points = c.Points,
                Ordinal = c.Ordinal,
                subgrid = new
                {
                    subtotal = 1,
                    subpage = 1,
                    cell = qstList.Where(
                              q => q.QuestionId == c.QuestionId).Select(
                              q => q.Answers).Select((d, j) => new
                              {
                                  Id = d.Select(a => a.AnswerId),
                                  Text = d.Select(a => a.Text),
                                  Correctness = d.Select(a => a.Correctness),
                                  Ordinal = d.Select(a => a.Ordinal)
                              }).ToArray()
                }
            }).ToArray()
};

行很好,但子网格的单元格数组是奇数。我期待的是:

{[Id, Text, Correctness, Ordinal], ..., [Id, Text, Correctness, Ordinal]}

但事实证明是:

{[Id, Id, ...], ..., [Ordinal, Ordinal, ...]}

如何获得预期的“布局”。谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

这将引导您找到正确的答案:

  • 为所有匿名类(Row,Subgrid,Cel等)创建普通类
  • 重构所有代码,以便一行只有一个Linq语句

现在调试als更容易,你可以看到所有Linq语句的每个子结果。我相信你会以这种方式找到正确的答案。 (如果没有,只需添加不起作用的单个Linq语句)。

答案 1 :(得分:0)

@Vladimir,谢谢!是的,SelectMany将执行:

subgrid = new
{
    subtotal = 1,
    subpage = 1,
    cell = qstList.Where(q => q.QuestionId == c.QuestionId).SelectMany(q => q.Answers).Select((d, j) => 
    new 
    {
        Id = d.AnswerId,
        Text = d.Text,
        Correctness = d.Correctness,
        Ordinal = d.Ordinal
     }).ToArray()
  }