1

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;
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Uni Le
  • 783
  • 6
  • 17
  • 30

1 Answers1

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;
        }
    }
}
Jay Riggs
  • 53,046
  • 9
  • 139
  • 151
  • i tried your code but it throws me a table with key header and nothing more – Uni Le Oct 10 '12 at 16:55
  • @UniLe Then your sample code isn't representative if your actual code; when I use your code to create a DataTable and my code to update it I get the before and after results you say you need. I'm sure we can do what you need to do using LINQ, but that's not so important now that you've found a solution. – Jay Riggs Oct 10 '12 at 18:23