为了账号安全,请及时绑定邮箱和手机立即绑定

分组和组合值 DataTable,c#

分组和组合值 DataTable,c#

C#
至尊宝的传说 2021-10-24 14:15:35
前:Name    Class   AbilityBoy1      A1    SingBoy2      A1    SingBoy3      A2    SingGirl1     A2    SingGirl2     A2    Dance后:Name                Class   AbilityBoy1,Boy2             A1    SingBoy3,Girl1,Girl2      A1    Sing,Dance如何将表格前后分组?我用过:DataTable dt = GetDataTable();//获取数据dt.AsEnumerable()....//不知道怎么继续。请帮我
查看完整描述

2 回答

?
回首忆惘然

TA贡献1847条经验 获得超11个赞

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,这会容易得多。


查看完整回答
反对 回复 2021-10-24
?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

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


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


        });

希望这段代码有帮助


查看完整回答
反对 回复 2021-10-24
  • 2 回答
  • 0 关注
  • 173 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信