I have a for each loop that runs through the database to check for files that have been flagged for conversion. Currently I have the following code:
/* All files flagged for invidual conversion will be stored in here. */
ArrayList files = vc.getFilesForInvidualConversion();
foreach (FileInfoExtended file in files)
{
// As long as the status flag hasn't been changed it can continue.
if (abort == false)
{
if (vc.isFileInUse(file) == false)
{
// Converting the video file.
vc.convertVideoToFLV(file);
}
}
vc.getFilesForInvidualConversion();
}
In the first line you can see I fill an ArrayList with objects which it will run through with a for each. However, after each file in the list I want to check for possible new files that need to be converted. When I fill the ArrayList again the for each doesn’t seem to notice, it keeps working with the original files received from the first line of code. I’d rather want it to update the “files”-ArrayList so that it can convert the new files as well.
Is this possible?
EDIT: The anwsers you gave all work for this scenario, but I want to add something. Is it possible to remove a file from the list during the loop? And to make it so it won’t convert that one?
EDIT 2: This is what I have now:
List<FileInfoExtended> files = vc.getFilesForInvidualConversion();
while (files.Count > 0)
{
if (abort == false)
{
if (vc.isFileInUse(files[0]))
{
vc.convertVideoToFLV(files[0]);
}
}
files = vc.getFilesForInvidualConversion();
}
And it works in both cases (when a file is added to the list and when a file is removed from the list). I don’t know if it is performance wise a good solution, but right now it suits my needs. Unless there are some issues I’m overlooking?
Any comment will be appreciated!
Kind regards,
Floris
You can use a standard ‘for’ loop. foreach loops require the collection to be immutable during traversal. A ‘for’ loop doesn’t have this constraint. However, getting the ending condition constraints on a ‘for’ loop might be difficult in this case.
I would consider keeping a list of the files already processed so that when you make you second pass, you can just check to see if you have already handled a particular file.