使用DataTable.GetChanges()
为我提供了所有修改行的列表。是否有一些内置方法可以在行级执行相同的操作;检查哪些列已被修改,而不是手动比较循环中的ItemArray
?
答案 0 :(得分:7)
没有
您可以使用此代码将这些值与之前的版本进行比较:
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();
}
}
改编自Verify which columns have changed in a datatable or datarow。
示例:强>
DataTable table;
table.GetChangedColumns()
List<DataRow> listOfRows;
listOfRows.GetChangedColumns()
DataRow row;
row.GetChangedColumns()