替换ICollection中的元素

Mat*_*ero 3 .net c# collections icollection

假设我有一个ICollection<SomeClass>

我有以下两个变量:

SomeClass old;
SomeClass new;
Run Code Online (Sandbox Code Playgroud)

如何使用来实现类似以下的功能ICollection<SomeClass>

// old is guaranteed to be inside collection
collection.Replace(old, new);
Run Code Online (Sandbox Code Playgroud)

ken*_*n2k 5

这里没有黑魔法:ICollection<T>没有顺序,仅提供Add/ Remove方法。您唯一的解决方案是检查实际的实现是否还包括其他内容,例如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);
    }

}
Run Code Online (Sandbox Code Playgroud)