替换ICollection中的元素

时间:2015-12-23 12:33:41

标签: c# .net collections

假设我有ICollection<SomeClass>

我有以下两个变量:

SomeClass old;
SomeClass new;

如何使用ICollection<SomeClass>来实现以下内容?

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

3 个答案:

答案 0 :(得分:3)

此处没有黑魔法: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);
    }

}

答案 1 :(得分:0)

ICollection<T>界面非常有限,您必须使用Remove()Add()

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

答案 2 :(得分:-1)

这样做:

TypeApplications