DataTable分组结果 [英] DataTable group the result

查看:454
本文介绍了DataTable分组结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to group in Datatable by Name, LastName and the rest should be in same row. Can someone help me with it?

我的DataTable:

My DataTable:

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

我想按名称拥有DataTable组:

I want to have DataTable group by Name:

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


推荐答案

添加这些行而不是注释( //某事必须存在):

Add these lines instead of the comment (//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

to get three new columns on the output that aggregate values from the columns 1, 3 and 2.

如果你在一个列的一个列中有多个值,所有值将以逗号()分隔。

If you have multiple values in one of the columns for a group, all the values will be shown and separated by comma (,).

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

If you are sure that there's at most one value per column per group, then you can simply do:

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分组结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆