[英]How to replace duplicates in datatable
I have Datatable 1:-----------------------------should be like that: 我有数据表1:-----------------------------应该是这样的:
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? 如何用“”替换“ 1”或如果已经存在则为空? 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? 我尝试过linq,但找不到正确的方法,可能是不同的方法还是分组方法?
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;
Here's how you can do this using LINQ: 使用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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.