Matias Cicero
Matias Cicero

Reputation: 26281

Replacing an element in ICollection

Suppose I have an ICollection<SomeClass>.

I have the following two variables:

SomeClass old;
SomeClass new;

How can I achieve something like the following using an ICollection<SomeClass>?

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

Upvotes: 5

Views: 8396

Answers (3)

Armindo Pacuco
Armindo Pacuco

Reputation: 1

Do that:

    yourCollection.ToList()[index] = newValue;

Upvotes: -2

ken2k
ken2k

Reputation: 48975

There is no black magic here: ICollection<T> 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<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);
    }

}

Upvotes: 9

Jakub Lortz
Jakub Lortz

Reputation: 14896

The ICollection<T> interface is quite limited, you will have to use Remove() and Add()

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

Upvotes: 0

Related Questions