C# 如何最有效地从数据表中删除条目?
我正在开发一个或多或少的遗留C#应用程序,偶然发现了我不久前编写的一段代码。但不知怎的,我觉得这不是一个好办法 我怎样才能使这段代码更好C# 如何最有效地从数据表中删除条目?,c#,datatable,rowdeleting,C#,Datatable,Rowdeleting,我正在开发一个或多或少的遗留C#应用程序,偶然发现了我不久前编写的一段代码。但不知怎的,我觉得这不是一个好办法 我怎样才能使这段代码更好 public static void RemoveEntries(DataTable source, ref DataTable destination, int indexSource, int indexDestination) { var arVals = new int[source.Rows.Count];
public static void RemoveEntries(DataTable source, ref DataTable destination, int indexSource, int indexDestination)
{
var arVals = new int[source.Rows.Count];
var i = 0;
foreach (DataRow sourceRow in source.Rows)
{
if (sourceRow.RowState != DataRowState.Deleted)
arVals.SetValue(sourceRow[indexSource], i);
i += 1;
}
foreach (
var destinationRow in
from DataRow row3
in destination.Rows
where arVals.Contains((int) row3[indexDestination])
where row3.RowState != DataRowState.Deleted
select row3
)
destinationRow.Delete();
}
提前感谢,,
bb不使用arVals,您不能删除第一个循环中的行吗?是否有某种主键字段可以唯一标识两个表中存在的行?“代码更好”表示代码或性能更少?“代码更好”表示代码更少,更易于理解。我不太清楚为什么我甚至需要2个数据表。。
public static void RemoveEntries(
DataTable source, int sourceIndex,
DataTable destination, int destinationIndex) {
var query=
from DataRow rowDestination in destination.Rows
where rowDestination.RowState!=DataRowState.Deleted
from DataRow rowSource in source.Rows
where rowSource.RowState!=DataRowState.Deleted
where rowSource[sourceIndex]==rowDestination[destinationIndex]
select rowDestination;
foreach(var row in query.ToArray())
row.Delete();
}