在开始时有效地收集插入物和移除物

时间:2011-06-05 08:23:36

标签: c# collections

对于经常在集合开头插入和删除对象的代码,您会推荐哪些集合。

以下是一些说明我的要求的代码

while (collection.Count != 0)
{
   object obj = collection[0];
   collection.RemoveAt(0);

   ...

   if (somethingWith(obj))
       collection.Insert(0, anotherObj);

   ...  
}

在0以外的位置没有插入或删除。集合未排序。

你会推荐什么?

编辑:

我真的不需要对这个系列做任何想象。该集合用于对应处理的对象进行排队(并在处理期间填充集合)。

1 个答案:

答案 0 :(得分:8)

您似乎只想实现LIFO容器,因此可以使用Stack<T>

while (stack.Count > 0) {
    object obj = stack.Pop();
    // ...
    if (SomethingWith(obj)) {
        stack.Push(anotherObj);
    }
}