tags:

views:

883

answers:

5

Hi,

I have an array of files in the object FileInfo[].

In my service, I am currently looping through the files and processing them.

I want to loop through the files, and remove them from the collection as they are processed.

I think a queue is ideal for this, but how can I loop through a queue collection?

(never used a queue in C# before)

+1  A: 

You iterate through a queue the same way you iterate through most other collections in C# - using foreach:

foreach (FileInfo file in queue)
{
    // Do stuff
}

If you use the above code, however, you can't add to the queue within the body. If you want to do that, you should do something like:

while (queue.Count > 0)
{
    FileInfo file = queue.Dequeue();
    // You can still use queue.Enqueue() here
}

(Both of these assume that queue is of type Queue<FileInfo>.)

Jon Skeet
+1  A: 

With a Queue pop the items from the queue as you process them.

while (queue.Count > 0) {
  T item = queue.Dequeue()
  ProcessItem(item)
}

Also queue implements IEnumberable, so you can also use foreach, but (in general) you can't modify a collection you are enumerating.

Richard
+2  A: 
using System.Collections.Generic;

private void DoSomething(FileInfo [] files)
{
    Queue<FileInfo> f = new Queue<FileInfo>(files);

    while (f.Count > 0) {
        FileInfo current = f.Dequeue();

        // Process 'current'
    }
}
Sean Bright
+1  A: 
Queue<FileInfo> q = new Queue<FileInfo>(yourFileInfoArray);

while (q.Count > 0)
{
    FileInfo fi = q.Dequeue();
    // do stuff with fi
}
LukeH
+1  A: 

The other way to do this is simply iterate through the FileInfo array backwards, and pop off each element.

FileInfo[] f = ... 

for(int i = f.Length - 1; i >= 0; i--)
{
   // Do something
   f.RemoveAt[i];
}
Chris Holmes