3

一致するキーに基づいてアイテムを追加、削除、または置換する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);
    }
}
4

1 に答える 1

2

古いものと新しいものが逆になっています。これ:

var updatedItems = (from eachKey in targetDictionary.Keys
                                              .Intersect(sourceDictionary.Keys)
                    select new
                    {
                        Old = targetDictionary[eachKey],
                        New = sourceDictionary[eachKey]
                    }).ToList();

これである必要があります:

var updatedItems = (from eachKey in targetDictionary.Keys
                                              .Intersect(sourceDictionary.Keys)
                    select new
                    {
                        New = targetDictionary[eachKey],
                        Old = sourceDictionary[eachKey]
                    }).ToList();

現在、-1 になる新しい値のインデックスを探しています...

于 2009-11-02T07:06:15.563 に答える