我有一个数据表如下。
Name Val ID
--------------
Raja 0 101
---------------
Ram 0 102
---------------
Ray 0 103
---------------
Raja 0 104
---------------
如果同名重复,我想影响我的数据表列。在我的数据表中,Raja名称重复第二次,所以我想将名称更改为Raja(2)。
O / p:
Name Val ID
--------------
Raja 0 101
---------------
Ram 0 102
---------------
Ray 0 103
---------------
Raja(2) 0 104
---------------
请指导我这个。
DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Item", typeof(string));
table.Columns.Add("Qty", typeof(string));
table.Rows.Add("AAA", "Indocin", "David");
table.Rows.Add("XXX", "Enebrel", "Sam");
table.Rows.Add("AAA", "Hydralazine", "Christoff");
table.Rows.Add("CCC", "Combivent", "Janet");
table.Rows.Add("AAA", "Dilantin", "Melanie");
// Query with Linq
var newNames = table.AsEnumerable()
.Select((row, rowIndex) => new { rowIndex, index }) // 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)
/*Error*/ .Select((x, dupIndex) => new { x.rowIndex, newName = $"{g.Key}({dupIndex + 1})" }));
foreach(var x in newNames)
table.Rows[x.index].SetField("Name", x.newName);
/***********/
这是我的代码..
答案 0 :(得分:1)
您可以使用Linq-To-DataTable
,尤其是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);
我按名称分组,然后只获取重复的行(+它们的索引)。从那些重复组中我除了第一个之外的所有(因为该名称仍然存在)。