一致するキーに基づいてアイテムを追加、削除、または置換するObservableCollectionのRefresh()拡張メソッドに取り組んでいます(つまり、DataGridにバインドされている場合、グリッドは再スクロールされず、アイテムは位置を変更しません。それらは削除されました)。
問題は、ObservableCollectionのアイテムを置き換えると、最後のアイテムがArgumentOutOfRangeExceptionをスローすることですが、ここで何が欠落していますか?
public static void Refresh<TItem, TKey>(this ObservableCollection<TItem> target, IEnumerable<TItem> source, Func<TItem, TKey> keySelector)
{
var sourceDictionary = source.ToDictionary(keySelector);
var targetDictionary = target.ToDictionary(keySelector);
var newItems = sourceDictionary.Keys.Except(targetDictionary.Keys).Select(k => sourceDictionary[k]).ToList();
var removedItems = targetDictionary.Keys.Except(sourceDictionary.Keys).Select(k => targetDictionary[k]).ToList();
var updatedItems = (from eachKey in targetDictionary.Keys.Intersect(sourceDictionary.Keys)
select new
{
Old = targetDictionary[eachKey],
New = sourceDictionary[eachKey]
}).ToList();
foreach (var updatedItem in updatedItems)
{
int index = target.IndexOf(updatedItem.Old);
target[index] = updatedItem.New; // ArgumentOutOfRangeException is thrown here
}
foreach (var removedItem in removedItems)
{
target.Remove(removedItem);
}
foreach (var newItem in newItems)
{
target.Add(newItem);
}
}