使用linq在数据透视表上获取错误

时间:2017-06-23 19:20:37

标签: c# .net linq

我使用linq从普通数据表进行了数据透视表。但有时候,我会收到类似的错误。

There is no row at position 5(or any number like 7,8,11 etc..)
-----------------------------------------------------------
object reference not set to an instance of an object

我没有理解它,为什么有时候它的效果非常好,条件相同,例如< sample_time'等等,为什么有时候不起作用。

这是我用linq将行交换到列的代码。此外,当我调试时,我发现了抛出错误的部分。

 var dtExist = dtTopAll.AsEnumerable().Where(l => l.Field<DateTime>("SAMPLE_TIME") >= minDate && l.Field<DateTime>("SAMPLE_TIME") <= maxDate).Any();

            if (dtExist == true)
            {
                var dt = (from dr1 in dtTopAll.AsEnumerable()
                          where dr1.Field<DateTime>("SAMPLE_TIME") >= minDate && dr1.Field<DateTime>("SAMPLE_TIME") <= maxDate
                          group dr1 by new
                          {
                              WAIT_CLASS = dr1.Field<string>("WAIT_CLASS"),
                              SAMPLE_TIME = dr1.Field<DateTime>("SAMPLE_TIME")
                          } into g
                          select new
                          {
                              SAMPLE_TIME = g.Key.SAMPLE_TIME,
                              WAIT_CLASS = g.Key.WAIT_CLASS,
                              WAITS = g.Sum(z => z.Field<double>("WAITS") / 100)
                          }).ToDataTable();

                var groups = dt.AsEnumerable().GroupBy(x => x.Field<DateTime>("SAMPLE_TIME")).ToList();

                foreach (var group in groups) // From this line to end, throws an error .
                {
                    DataRow newRow = dtPivotCustom.Rows.Add();
                    newRow[0] = group.Key;
                    foreach (string item in items)
                    {
                        newRow[item] = group.Where(x => x.Field<string>("WAIT_CLASS") == item).Select(x => x.Field<double>("WAITS")).Sum();
                    }
                }
            }

0 个答案:

没有答案