Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何最有效地从数据表中删除条目?_C#_Datatable_Rowdeleting - Fatal编程技术网

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];

我正在开发一个或多或少的遗留C#应用程序,偶然发现了我不久前编写的一段代码。但不知怎的,我觉得这不是一个好办法

我怎样才能使这段代码更好

        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();
}