分组和合并值DataTable,C#

时间:2018-07-23 15:55:01

标签: c# winforms datatable

之前:

Name    Class   Ability
Boy1      A1    Sing
Boy2      A1    Sing
Boy3      A2    Sing
Girl1     A2    Sing
Girl2     A2    Dance

之后:

Name                Class   Ability
Boy1,Boy2             A1    Sing
Boy3,Girl1,Girl2      A1    Sing,Dance

如何对表进行分组? 我用过:DataTable dt = GetDataTable(); //获取数据 dt.AsEnumerable().... //我不知道如何继续。 请帮助我

2 个答案:

答案 0 :(得分:1)

var result = dt.AsEnumerable()
     .GroupBy(d => d.Field<string>("Class"))
     .Select(g => new
     {
         Name = string.Join(",", 
            g.Select(gn => gn.Field<string>("Name")).Distinct()),
         Class = g.Key,
         Teacher = string.Join(",", 
            g.Select(gt => gt.Field<string>("Ability")).Distinct())
     });

注意:如果直接使用Linq而不是DataTable,这会容易得多。

答案 1 :(得分:0)

我为样本创建了一个虚拟数据

        DataTable dtNew, dt = new DataTable();
        dt.Columns.Add("Id", typeof(string));
        dt.Columns.Add("Category",typeof(string));
        dt.Columns.Add("Type",typeof(string));
        dtNew = dt.Clone();


        dt.Rows.Add("323021", "Doors", "900");
        dt.Rows.Add("323022", "Doors", "900");
        dt.Rows.Add("323023", "Doors", "1000");
        dt.Rows.Add("323024", "Doors", "1000");

        dt.Rows.Add("323025", "Walls", "200");
        dt.Rows.Add("323026", "Walls", "200");
        dt.Rows.Add("323027", "Walls", "200");
        dt.Rows.Add("323028", "Walls", "200");

        dt.Rows.Add("323026", "Columns", "300x300");
        dt.Rows.Add("323027", "Columns", "300x300");
        dt.Rows.Add("323028", "Columns", "500x500");

此方案的解决方案

        //Case 1: Category and Type
        var caretoryTypeResult = (from b in dt.AsEnumerable()
                              group b by new
                              {
                                  Category = b.Field<string>("Category"),
                                  Type = b.Field<string>("Type")
                              }
                                  into grpCategoryType
                                  select new
                                  {
                                      grpCategoryType.Key.Category,
                                      grpCategoryType.Key.Type,
                                      grpCategoryType
                                  }).ToList();

        caretoryTypeResult.ForEach(list => {
            var category = list.grpCategoryType.AsEnumerable().Select(m => m.Field<string>("Id")).ToList();
            dtNew.Rows.Add(string.Join(",", category), list.Category, list.Type);

        });

希望此代码有帮助