I’m having a problem with finding out which children to add, update and delete when I’m dealing with two lists one with the old chidren (from db) and the other list with the modified children (from user input).
Currently I have to loop through the lists and compare to find the difference.
Does anyone know of a better way of doing this without having to loop through the lists?
The IEnumerable.Except extension method is perfect for this. In most cases you will want to use the overload that accepts an
IEqualityComparer<T>to compare by identity, unless you have carefully overridden Equals and GetHashCode in your objects.Given
The code is:
The
ToArray()calls are there so that you can make changes to the original list while iterating the add and remove lists.Edit: Below are two utility classes that make this operation easy. Usage is