c#datatable group by many columns

时间:2014-08-02 20:14:41

标签: c# .net

这是我的旧代码

DateTime epoch = new DateTime(1970, 1, 1);
var result = (from row in InBoundtable.AsEnumerable()
              group row by row.Field<string>("Date") into grp
              select new
              {
                  AbandonCalls = grp.Sum((r) => Double.Parse(r["AvgAbandonedCalls"].ToString())),
                  Date = ((DateTime.Parse(grp.Key.ToString())) - epoch).TotalMilliseconds
              }).ToList();

如您所见,我正在Date列上制作小组。

我可以在DateSlice列上制作论坛吗?其中两者都是字符串值

1 个答案:

答案 0 :(得分:1)

使用这两列创建匿名类型。这两列都将成为该组“密钥”的一部分,因此您必须单独访问它们。

DateTime epoch = new DateTime(1970, 1, 1);

var result = (from row in new DataTable().AsEnumerable()
              group row by new
                           {
                               Date = row.Field<string>("Date"),
                               Slice = row.Field<string>("Slice")
                           }
              into grp
              select new
                     {
                         AbandonCalls = grp.Sum((r) => Double.Parse(r["AvgAbandonedCalls"].ToString())),
                         Date = ((DateTime.Parse(grp.Key.Date)) - epoch).TotalMilliseconds,
                         grp.Key.Slice
                     }).ToList();