Replacing an element in ICollection

后端 未结 3 902
我在风中等你
我在风中等你 2021-01-20 19:06

Suppose I have an ICollection.

I have the following two variables:

SomeClass old;
SomeClass new;

How

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 19:34

    There is no black magic here: ICollection is not ordered and only provides Add/Remove methods. Your only solution would be to check if the actual implementation is something more, such as IList:

    public static void Swap(this ICollection collection, T oldValue, T newValue)
    {
        // In case the collection is ordered, we'll be able to preserve the order
        var collectionAsList = collection as IList;
        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);
        }
    
    }
    

提交回复
热议问题