1

我想按名称、姓氏对数据表进行分组,其余的应该在同一行。有人可以帮我吗?

我的数据表:

 Name   LastName    1    3    2
 kiki    ha         FF
 lola    mi             AA
 ka      xe                   UU
 kiki    ha                   SS

我想按名称对 DataTable 进行分组:

Name   LastName   1    3     2
kiki    ha        FF         SS 
lola    mi             AA 
ka      xe                   UU

我的新代码:

var result11 = from t1 in newtable.AsEnumerable()
               group t1 by new { Name = t1.Field<String>("Name"), LastName = t1.Field<String>("LastName") } into grp
               select new
               {
                   Name = grp.Key.Name,
                   LastName = grp.Key.LastName,

                   //Something must be there     
               };
4

2 回答 2

2

添加这些行而不是注释 ( //something must be there):

C1 = String.Join(",", grp.Select(r=>r.Field<String>("1"))),
C2 = String.Join(",", grp.Select(r=>r.Field<String>("2"))),
C3 = String.Join(",", grp.Select(r=>r.Field<String>("3")))

在输出中获取三个新列,这些列汇总了列13的值2

如果您在一个组的一列中有多个值,则所有值都将显示并用逗号 ( ,) 分隔。

如果您确定每组每列最多有一个值,那么您可以简单地执行以下操作:

C1 = grp.Max(r => r.Field<String>("1")),
C3 = grp.Max(r => r.Field<String>("3")),
C2 = grp.Max(r => r.Field<String>("2"))
于 2012-10-16T12:10:57.663 回答
1

如果你想要一个DataTable结果,这会给出你想要的结果:

var lastNameGroups = from row in table1.AsEnumerable()
                     group row by new {
                        Name= row.Field<String>("Name"), 
                        LastName = row.Field<String>("LastName")
                     } into LastNameGroups
                     select LastNameGroups;

var table2 = table1.Clone();
foreach (var lng in lastNameGroups)
{
    var row = table2.Rows.Add();
    row.SetField("Name", lng.Key.Name);
    row.SetField("LastName", lng.Key.LastName);
    var ones = lng.Where(r => !string.IsNullOrEmpty(r.Field<String>("1")));
    if(ones.Any())
        row.SetField("1", ones.First().Field<String>("1"));
    var twos = lng.Where(r => !string.IsNullOrEmpty(r.Field<String>("2")));
    if (twos.Any())
        row.SetField("2", twos.First().Field<String>("2"));
    var threes = lng.Where(r => !string.IsNullOrEmpty(r.Field<String>("3")));
    if (threes.Any())
        row.SetField("3", threes.First().Field<String>("3"));
}
于 2012-10-16T12:31:29.753 回答