在 ICollection 中替换一个元素

5
假设我有一个ICollection<SomeClass>
我有以下两个变量:
SomeClass old;
SomeClass new;

我如何使用 ICollection<SomeClass> 实现以下内容?
// old is guaranteed to be inside collection
collection.Replace(old, new);

你正在使用哪种 ICollection<T> 的实现? - stuartd
@Valentin 我在谈论使用 ICollection 接口进行操作。 - Matias Cicero
这取决于实现该接口的类型。 - Hamlet Hakobyan
@stuartd 这个有关系吗?我正在使用HashSet<SomeClass> - Matias Cicero
3个回答

9
这里没有什么黑魔法: ICollection<T> 不是有序的,只提供 Add/Remove 方法。你唯一的解决方案就是检查实际的实现是否是 更多,比如 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
这确实帮助我使用索引从集合中删除项目。 - Santiago Rebella

0

ICollection<T> 接口相当有限,您将不得不使用 Remove()Add()

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

我考虑过这个问题,但是new会被添加到集合的末尾,而不是old的位置。 - Matias Cicero
1
是的,这就是为什么我删除了我的评论。但更准确的说法是ICollection不能保证有序。为此,您应该使用更具体的东西,它在所有使用的集合类型之间都很常见,并且实际上支持顺序。也许应该使用IList<T> - gmiley
@MatiasCicero,尽管它有一定的顺序,但这只是实现细节,当您设计类时不应参考它。 - Hamlet Hakobyan
1
如果你需要一个有序的集合,应该使用 IList<T> - Jakub Lortz
@MatiasCicero 你提到你使用 HashSet<T> 作为 ICollection<T> 的实现。根据定义,集合是无序的。从MSDN HashSet文档中可以看到:“集合是一个不包含重复元素且元素没有特定顺序的集合。” - Jakub Lortz
不总是有效,即如果您在foreach语句内部删除它。 - Santiago Rebella

-1

做这个:

    yourCollection.ToList()[index] = newValue;

3
虽然这个答案可能对提问者有所帮助,但考虑到提高回答的质量,可以提供解决问题所采取的步骤。 - Derviş Kayımbaşıoğlu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接