我正在为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);
}
}