Bobrovsky
Bobrovsky

Reputation: 14246

Efficient collection for inserts and removals at the beginning

What collection would you recommend for a code that frequently inserts and removes objects at the beginning of the collection only.

Here is some code to illustrate my requirements

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

   ...

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

   ...  
}

There is no inserts or removals at positions other than 0. Collection is not sorted.

What would you recommend?

EDIT:

I don't really need to do anything fancy with the collection. The collection is used to queue objects that should be processed (and collection gets populated during processing).

Upvotes: 3

Views: 136

Answers (1)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262979

It seems you only want to implement a LIFO container, so you can use a Stack<T>:

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

Upvotes: 8

Related Questions