替换 ICollection 中的元素

Replacing an element in ICollection

假设我有一个 ICollection<SomeClass>

我有以下两个变量:

SomeClass old;
SomeClass new;

如何使用 ICollection<SomeClass> 实现类似以下的效果?

// old is guaranteed to be inside collection
collection.Replace(old, new);

ICollection<T>接口非常有限,您将不得不使用Remove()Add()

collection.Remove(old);
collection.Add(new);

这里没有黑魔法:ICollection<T> 没有顺序,只提供 Add/Remove 方法。您唯一的解决方案是检查实际实现是否是 more,例如 IList<T>:

public static void Swap<T>(this ICollection<T> collection, T oldValue, T newValue)
{
    // In case the collection is ordered, we'll be able to preserve the order
    var collectionAsList = collection as IList<T>;
    if (collectionAsList != null)
    {
        var oldIndex = collectionAsList.IndexOf(oldValue);
        collectionAsList.RemoveAt(oldIndex);
        collectionAsList.Insert(oldIndex, newValue);
    }
    else
    {
        // No luck, so just remove then add
        collection.Remove(oldValue);
        collection.Add(newValue);
    }

}

这样做:

    yourCollection.ToList()[index] = newValue;