Linq上的多列组

时间:2017-06-21 07:01:50

标签: c# .net linq

我想在多列上使用group by,但是无法理解我应该如何选择SAMPLE_TIME,即使我将Manuel日期写入采样时间我也会得到以下错误;

System.InvalidCastException: 'System.ValueTuple`2[System.String,System.String]' 'System.String'

目前我使用的是如下所示;

var dt = (from dr1 in dtTopAll.AsEnumerable()
                          where  dr1.Field<DateTime>("SAMPLE_TIME") <= maxDate
                          group dr1 by ("WAIT_CLASS", "SAMPLE_TIME")  into g
                          select new
                          {
                              SAMPLE_TIME = // How can i select sample_time,
                              WAIT_CLASS = g.Key,
                              WAITS = g.Sum(z => z.Field<double>("WAITS") / 100)
                          }).ToDataTable();

2 个答案:

答案 0 :(得分:1)

你试过这个:

var dt = (from dr1 in dtTopAll.AsEnumerable()
          where  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();

答案 1 :(得分:0)

您需要的是通过使用group by new在组上创建新的匿名类型,如果要选择,则可以使用别名。请检查一下; Group By Multiple Column In LINQ in C#