Replacing an element in ICollection

限于喜欢 提交于 2019-12-01 21:26:33

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

}

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

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

Do that:

    yourCollection.ToList()[index] = newValue;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!