C# 分组并合并值数据表,c
之前: 之后:C# 分组并合并值数据表,c,c#,winforms,datatable,C#,Winforms,Datatable,之前: 之后: Name Class Ability Boy1 A1 Sing Boy2 A1 Sing Boy3 A2 Sing Girl1 A2 Sing Girl2 A2 Dance 我怎样才能把桌子前后分组? 我使用:DataTable dt=GetDataTable//获取数据 dt.AsEnumerable...//我不知道如何继续。 请帮帮我 Name Class
Name Class Ability
Boy1 A1 Sing
Boy2 A1 Sing
Boy3 A2 Sing
Girl1 A2 Sing
Girl2 A2 Dance
我怎样才能把桌子前后分组?
我使用:DataTable dt=GetDataTable//获取数据
dt.AsEnumerable...//我不知道如何继续。
请帮帮我
Name Class Ability
Boy1,Boy2 A1 Sing
Boy3,Girl1,Girl2 A1 Sing,Dance
注意:如果您直接使用Linq而不是DataTable,这将更加容易。我为示例创建了一个虚拟数据
此场景的解决方案
希望此代码有帮助请在问题文本中发布您的数据,而不是以图像的形式发布。如果其他人不需要转录你的数据,他们会更容易提供帮助。谢谢你,简,第一次给你打电话,塞汀,这就是我所期望的。嗨,塞汀,我面临这个问题,它相当复杂。我会尽力解释的。这就是我想要的结果:我有一个具有相当大列的DataTable。您的解决方案正在使用固定数量的列。@ShaiNguyễn、 对不起,我不明白你在谷歌电子表格中的意思。如果您的意思是,不只是类别,而是希望按类别和类型分组,那么您可以通过.GroupBy d=>new{Category=d.FieldCategory,Type=d.FieldType}来实现。
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())
});
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);
});