3

使用DataTable.GetChanges()给了我所有被修改的行的列表。是否有一些内置方法可以在行级别执行相同的操作?检查哪些列已被修改,而不是ItemArray在循环中手动比较?

4

1 回答 1

13

不。

您可以使用此代码将这些值与其以前的版本进行比较:

public static class DataRowExtensions
{
    private static bool hasCellChanged(DataRow row, DataColumn col)
    {
        if (!row.HasVersion(DataRowVersion.Original))
        {
            // Row has been added. All columns have changed. 
            return true;
        }
        if (!row.HasVersion(DataRowVersion.Current))
        {
            // Row has been removed. No columns have changed.
            return false;
        }
        var originalVersion = row[col, DataRowVersion.Original];
        var currentVersion = row[col, DataRowVersion.Current];
        if (originalVersion == DBNull.Value && currentVersion == DBNull.Value)  
        {
            return false;
        }
        else if (originalVersion != DBNull.Value && currentVersion != DBNull.Value)  
        {  
            return !originalVersion.Equals(currentVersion);
        }
        return true;
    }

    public static IEnumerable<DataColumn> GetChangedColumns(this DataRow row)
    {
        return row.Table.Columns.Cast<DataColumn>()
            .Where(col => hasCellChanged(row, col));
    }

    public static IEnumerable<DataColumn> GetChangedColumns(this IEnumerable<DataRow> rows)
    {
        return rows.SelectMany(row => row.GetChangedColumns())
            .Distinct();
    }

    public static IEnumerable<DataColumn> GetChangedColumns(this DataTable table)
    {
        return table.GetChanges().Rows
            .Cast<DataRow>()
            .GetChangedColumns();
    }
}

改编自验证数据表或数据行中哪些列已更改

例子:

DataTable table;
table.GetChangedColumns()

List<DataRow> listOfRows;
listOfRows.GetChangedColumns()

DataRow row;
row.GetChangedColumns()
于 2013-06-16T14:00:15.653 回答