Shai Nguyễn
Shai Nguyễn

Reputation: 105

Group and combine value DataTable, c#

Before:

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

After:

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

How can I group table before to after? I used: DataTable dt = GetDataTable();//get the data dt.AsEnumerable()....//I don't know how do continue. Please help me

Upvotes: 0

Views: 192

Answers (2)

davinceleecode
davinceleecode

Reputation: 807

I created a dummy data for sample

        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");

Solution for this scenario

        //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);

        });

Hope this code helps

Upvotes: 0

Cetin Basoz
Cetin Basoz

Reputation: 23827

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())
     });

NOTE: This would much easier if you used directly Linq instead of a DataTable.

Upvotes: 1

Related Questions