c# - 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
希望我能解释一下:)。非常感谢 :)。
解决方案
这是一种方法...
//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
}
}
推荐阅读
- php - 在 PHP 中删除 HTML 属性
- r - 来自 tidyverse 和 as.numeric() 的过滤函数
- mysql - 因为我不能在 Mysql 的 SELECT 中使用“<> Null”?
- android - 如何使用 Android.mk 编译 Android 应用程序源以在 Android 系统源中使用 androidx?
- php - 如何在循环中计算特定单词在php中
- java - 如何使用 JPanel 将线函数列表变成一个 drawPolygon 函数?
- python - 如何防止函数向python中的字典添加重复键
- python - 使用 CV 获得更高的 RMSE 分数可以传达什么信息
- python - 熊猫库中的合并函数
- r - 使用 Selenium 提取延迟加载的内容?