How to replace duplicates in datatable

百般思念 提交于 2019-12-11 06:00:01

问题


I have Datatable 1:-----------------------------should be like that:

ID   Name  Lastname             ID     Name   Lastname
-------------------             -----------------------
1  |  koki  ha                  1   |   koki     ha
-------------------                 | ----------------- //merge Rows[0][0]          
1  |  lola  mi                      |   lola     mi     //with Rows[1][0] if the same
-------------------             -----------------------                      
2  |  ka    xe                  2       ka      xe

how to replace "1" with "" or empty if is already exist? I spend for this for 2 hours but can't find the solution. I tried with linq but dont find the key to do it right, maybe distinct or group?

DataTable table = new DataTable("table");
table.Columns.Add("ID", typeof(Int32));
table.Columns.Add("Name", typeof(String)); 
table.Columns.Add("Lastname", typeof(String));

object[] o1 = { 1, "Kiki", "ha"};
        object[] o2 = { 1,"lola","mi"};
        object[] o4 = { 2, "ka", "xe" };
table.Rows.Add(o1);
        table.Rows.Add(o2);
        table.Rows.Add(o4);
dataGridView2.DataSource = table;

回答1:


Here's how you can do this using LINQ:

var dataRows = table.Rows.Cast<System.Data.DataRow>()
                         .GroupBy(r => r[0])
                         .Where(g => g.Count() > 1); 

foreach (var dataRowGroup in dataRows) {
    int idx = 0;
    foreach (DataRow row in dataRowGroup) {
        if (idx++ > 0) {
            row[0] = DBNull.Value;
        }
    }
}


来源:https://stackoverflow.com/questions/12821636/how-to-replace-duplicates-in-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!