Linq分组和设置数据表

时间:2016-05-17 20:24:31

标签: linq grouping

enter image description here我有这个代码用于分组和汇总列:

var groupedData = from b in showit.AsEnumerable()
                  group b by b.Field<string>("Key") into g
                  select new
                  {
                    KeyName  = g.Key,
                    Calls_Chats_Answered = g.Sum(x => x.Field<int>("Calls_Chats_Answered"))
                  };

如何将groupedData传递给数据表?

1 个答案:

答案 0 :(得分:0)

        //Create DataTable
        DataTable dt = new DataTable();

        //Add DataColumns to DataTable
        dt.Columns.Add("KeyName", typeof(string));
        dt.Columns.Add("Calls_Chats_Answered", typeof(int));

        //Iterate over the query
        foreach (var v in groupedData)
        {
            //Create new DataRow
            DataRow dr = dt.NewRow();

            //Add values to DataRow
            dr["KeyName"] = v.KeyName;
            dr["Calls_Chats_Answered"] = v.Calls_Chats_Answered;

            //Add DataRow to DataTable
            dt.Rows.Add(dr);
        }