我想按名称、姓氏和其余部分分组,其余的应该在同一行中。有人可以帮我吗?
我的数据表:
Name LastName 1 3 2
kiki ha FF
lola mi AA
ka xe UU
kiki ha SS
我想让数据表按名称分组:
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
};
添加这些行而不是注释 ( //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")))
在输出上获取三个新列,这些列聚合了列中的值 1
、 3
和 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"))
如果你想要一个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"));
}