C# 如何从底线中特定id内的datatable中删除行
下面的代码选择第一行并删除下面具有特定id的另一行。我想要的是id中的最后一行C# 如何从底线中特定id内的datatable中删除行,c#,C#,下面的代码选择第一行并删除下面具有特定id的另一行。我想要的是id中的最后一行 var dtremove = RemoveDuplicateRows(dt, "id); 这是分机 public DataTable RemoveDuplicateRows(DataTable dt, string colName) { Hashtable hTable = new Hashtable(); ArrayList duplicateLi
var dtremove = RemoveDuplicateRows(dt, "id);
这是分机
public DataTable RemoveDuplicateRows(DataTable dt, string colName)
{
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();
//Add list of all the unique item value to hashtable, which stores combination of key, value pair.
//And add duplicate item value in arraylist.
foreach (DataRow drow in dt.Rows)
{
if (hTable.Contains(drow[colName]))
{
duplicateList.Add(drow);
}
else
hTable.Add(drow[colName], string.Empty);
}
//duplicateList.Sort();
//Removing a list of duplicate items from datatable.
foreach (DataRow dRow in duplicateList)
dt.Rows.Remove(dRow);
//Datatable which contains unique records will be return as output.
return dt;
}
datatable的示例
id date
------------
A 1/1/2018
A 1/2/2018
A 1/3/2018
B 2/1/2018
B 2/2/2018
我想要这样的结果
id date
------------
A 1/3/2018
B 2/2/2018
我尽量不改变太多的代码,非常确定它可以改进,但是下面的更改会查找值,如果它已经存在于字典中,则会替换它:因此,您将以最后一行而不是第一行结束。此外,它还返回一个新的数据表,原始数据表将保持不变
public DataTable RemoveDuplicateRows(DataTable dt, string colName)
{
var uniqueRows = new Dictionary<string, DataRow>();
foreach (DataRow thisRrow in dt.Rows)
{
if (uniqueRows.ContainsKey(colName))
{
uniqueRows[colName] = thisRrow;
}
else
{
uniqueRows.Add(colName, thisRrow);
}
}
DataTable copy = dt.Copy();
copy.Rows.Clear();
foreach (var thisRow in uniqueRows)
{
copy.Rows.Add(thisRow.Value);
}
//Datatable which contains unique records will be return as output.
return copy;
}
您尝试过什么?行为与预期行为有何不同?请提供一个。您可以使用Linq,但首先要开始编写一些代码。我已经在copy.Rows.AddthisRow;上更新了代码,它显示以下错误:无法将类型为“System.Collections.Generic.KeyValuePair”2[System.String,System.Data.DataRow]”的对象强制转换为类型为“System.IConvertible”。无法存储在id列中。所需类型为Int64。@mharry抱歉,请参见编辑。您需要使用copy.Rows.AddthisRow.Value;copy.Rows.AddthisRow.Value出现另一个问题;这一行已经属于另一个表。好的,我得到了它,而不是使用addrow,我只是使用ImportRow。