如何最有效地从DataTable中删除条目?

时间:2013-05-23 12:52:33

标签: c# datatable rowdeleting

我正在开发一个或多或少的传统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

1 个答案:

答案 0 :(得分:1)

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