简体   繁体   English

如何合并具有相似数据的行

[英]how to merge rows with similar data

I have a datatable with 3 columns ( first name, last name, age), I wanna browse through it and look for the rows that have the same first and last name, and replace them with one row that'll have the same first and last name. 我有一个包含3列(名字,姓氏,年龄)的数据表,我想浏览它并查找具有相同名字和姓氏的行,并将它们替换为一行具有相同的第一行和最后一行。姓。 As for the age column I wanna put all the ages in one cell and seperate them with a '|' 至于年龄栏我想把所有年龄都放在一个单元格中并用“|”分隔它们 or ';'. 要么 ';'。

Before: 之前:

John # Doe # 24 John#Doe#24

John # Doe # 35 John#Doe#35

After: 后:

John # Doe # 24|35 John#Doe#24 | 35

You can use LINQ and the extensions in the System.Data.DataSetExtensions.dll assembly like DataRowExtensions to group the rows and join the values you want like this: 您可以使用LINQ和System.Data.DataSetExtensions.dll程序集中的扩展(如DataRowExtensions)来对行进行分组并加入您想要的值,如下所示:

        var dt=new DataTable();
        dt.Columns.Add("A", typeof (string));
        dt.Columns.Add("B", typeof (string));
        dt.Columns.Add("C", typeof (int));

        dt.Rows.Add("John", "Doe", 23);
        dt.Rows.Add("John", "Doe", 24);
        dt.Rows.Add("John", "Doe", 25);

        var result = from row in dt.AsEnumerable()
                     group row by new {A=row.Field<string>("A"), B=row.Field<string>("B")} into grp
                     select new
                     {
                         CustomerName = grp.Key,
                         Items = String.Join(",",grp.Select(r=>r.Field<int>("C")))
                     };
        foreach (var t in result)
            Console.WriteLine(t.CustomerName + " " + t.Items);

The trick is to realize that what you ask is how to group the data and then aggregate the value column using something other than Count() or Sum() 诀窍是要意识到你问的是如何对数据进行分组,然后使用Count()或Sum()之外的其他东西来聚合值列

You'll find many questions in SO that ask how to group DataTable rows, eg. 你会在SO中找到很多问题,询问如何对DataTable行进行分组,例如。 this one that you can use as a reference to make more complex groupings 这个可以用作参考来制作更复杂的分组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM