UpdateCollection

public static void UpdateCollection<T>(this ICollection<T> originalCollection, ICollection<T> updatedCollection)
{
    if (originalCollection.IsReadOnly)
    {
        throw new InvalidOperationException("Cannot update a read-only collection.");
    }

    Collection<T> oldItems = new Collection<T>();
    Collection<T> newItems = new Collection<T>();

    foreach (var originalItem in originalCollection)
    {
        if (!updatedCollection.Contains(originalItem))
        {
            oldItems.Add(originalItem);
        }
    }

    foreach (var updatedItem in updatedCollection)
    {
        if (!originalCollection.Contains(updatedItem))
        {
            newItems.Add(updatedItem);
        }
    }

    foreach (var oldItem in oldItems)
    {
        originalCollection.Remove(oldItem);
    }

    foreach (var newItem in newItems)
    {
        originalCollection.Add(newItem);
    }
}
Example:
ObservableCollection<Uri> links = new ObservableCollection<Uri>(originalLinks)

...

// Do some operations on the collection

...

originalLinks.UpdateCollection(links);

Description

Updates items from the collection using a modified version of this collection. Useful in MVVM scenarios needing cancellable edition and delayed persistence.

Details

Double click on the code to select all.

 

;