DataTable对结果进行分组

时间:2012-10-16 12:02:43

标签: c# linq datatable linq-group

我想按名称,LastName分组Datatable,其余的应该在同一行。有人可以帮我吗?

我的数据表:

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

2 个答案:

答案 0 :(得分: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")))

在输出中获取三个新列,这些列汇总来自132列的值。

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

如果您确定每组每列最多只有一个值,那么您可以这样做:

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

答案 1 :(得分: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"));
}