Affect the datatable column value in C#

You can use Linq-To-DataTable especially GroupBy:

var newNames = table.AsEnumerable()
    .Select((row, rowIndex) => new { row, rowIndex }) // storing row and index of it in anonymous type
    .GroupBy(x => x.row.Field<string>("Name"))          // group by Name
    .Where(g => g.Count() > 1)                          // take only duplicates
    .SelectMany(g => g                                  // select all rows but first of duplicates
        .Where(x => x.rowIndex > 0)
        .Select((x, dupIndex) => new { x.rowIndex, newName = $"{g.Key}({dupIndex + 2})" }));    

foreach(var x in newNames)
    table.Rows[x.rowIndex].SetField("Name", x.newName);

I’m grouping by name, then taking only rows(+ their index) which are duplicated. From those duplicate-groups i take all but the first(because that name remains).

Browse More Popular Posts

Leave a Comment