首页 > 解决方案 > DataTable 搜索重命名重复项

问题描述

对不起这个菜鸟问题,但我没有为这个简单的问题找到一个灵魂。:(

在这个 dt 中,我想在第一列中找到重复项,并将其重命名为“_1”、“_2”、...。

**customer_id**   **shippingname**   **shippingaddress**

100001              John Wayne          John Wayne Street
100001              Billy Jean          Billy Jean Street
100002              John Conner         John Conner Street
100003              John Smith          John Smith Street
100001              Carrol Tree         Carrol Tree

最终结果必须如下所示:

**customer_id**   **shippingname**   **shippingaddress**

100001              John Wayne          John Wayne Street
100001_1            Billy Jean          Billy Jean Street
100002              John Conner         John Conner Street
100003              John Smith          John Smith Street
100001_2            Carrol Tree         Carrol Tree

希望我能解释一下:)。非常感谢 :)。

标签: c#

解决方案


这是一种方法...

//setting up your table...
DataTable dt = new DataTable();
dt.Columns.Add("customer_id", typeof(string));
dt.Columns.Add("shippingname", typeof(string));
dt.Columns.Add("shippingaddress", typeof(string));

dt.Rows.Add("100001", "John Wayne", "John Wayne Street");
dt.Rows.Add("100001", "Billy Jean", "Billy Jean Street");
dt.Rows.Add("100002", "John Conner", "John Conner Street");
dt.Rows.Add("100003", "John Smith", "John Smith Street");
dt.Rows.Add("100001", "Carrol Tree", "Carrol Tree");

//table initialized

//first we group our rows by customer_id ... 
var grps = dt.Rows.Cast<DataRow>().GroupBy(x => x.Field<string>("customer_id"));

//then we handle each group...
foreach (var grp in grps)
{
    int i = 1;//our suffix counter
    foreach (var row in grp.Skip(1)) // we go through all elements but the first...
    {
        row.SetField("customer_id", $"{grp.Key}_{i++}");//we set the new id
    }
}

推荐阅读