I have a form where users can modify a collection of objects using a DataGrid. When the form is opened I create a deep copy of the original collection and if the Cancel butt
The way I've dealt with this depends on the collections of objects having a unique ID. I also pass in the repository to deal with this as well, but for brevity I left it out. It's similiar to the following:
public static void MergeFields(IEnumerable persistedValues, IEnumerable newValues)
{
var leftIds = persistedValues.Select(x => x.Id).ToArray();
var rightIds = newValues.Select(x => x.Id).ToArray();
var toUpdate = rightIds.Intersect(leftIds).ToArray();
var toAdd = rightIds.Except(leftIds).ToArray();
var toDelete = leftIds.Except(rightIds).ToArray();
foreach(var id in toUpdate){
var leftScope = persistedValues.Single(x => x.ID == id);
var rightScope = newValues.Single(x => x.ID == id);
// Map appropriate values from rightScope over to leftScope
}
foreach(var id in toAdd) {
var rightScope = newValues.Single(x => x.ID == id);
// Add rightScope to the repository
}
foreach(var id in toDelete) {
var leftScope = persistedValues.Single(x => x.ID == id);
// Remove leftScope from the repository
}
// persist the repository
}