替换ICollection中的元素 [英] Replacing an element in ICollection

查看:79
本文介绍了替换ICollection中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 ICollection< SomeClass>

我有以下两个变量:

SomeClass old;
SomeClass new;

如何使用 ICollection< SomeClass>

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


推荐答案

这里没有黑魔法: ICollection< T> 未排序,仅提供 Add / 删除方法。唯一的解决方案是检查实际实现是否还更多,例如 IList< T>

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);
    }

}

这篇关于替换ICollection中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆