UpdateCollection
Updates items from the collection using a modified version of this collection. Useful in MVVM scenarios needing cancellable edition and delayed persistence.
Source
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);
Author: Lionel Ringenbach
Submitted on: 13 okt. 2011
Language: C#
Type: System.Collections.Generic.ICollection<T>
Views: 5197