foreach and how to elegantly know how far one has progressed in the collection

  • Thread starter Robert Sentgerath
  • Start date
R

Robert Sentgerath

Foreach is a relative handy construct to avoid having to create the classic
"for(int loop = 0; loop < collection.Length; loop++) construct. Though when
I use foreach instead I do not have access to a loop variable that allows me
to display a status message such as "Processing 4 out of 10".

Is there a more elegant way to code the following and avoid having to
declare the index variable?

DirectoryInfo diImport = new DirectoryInfo(processLogPath);
FileInfo[] fiImport = diImport.GetFiles(processLogMask);

int index = 0;
foreach(FileInfo file in fiImport)
{
index++;
DoSomething(file);

statusBar1.Text = String.Format("Processing {0} of {1}", index,
fiImport.Length);
}

Since the methods provided with the IEnumerator interface do not give back
an index, I have somehow the feeling there is no way to avoid declaring the
index type variable.

Any advise appreciated.
 
G

Guest

----- Robert Sentgerath wrote: ----

Foreach is a relative handy construct to avoid having to create the classi
"for(int loop = 0; loop < collection.Length; loop++) construct. Though whe
I use foreach instead I do not have access to a loop variable that allows m
to display a status message such as "Processing 4 out of 10"

Is there a more elegant way to code the following and avoid having t
declare the index variable

[snip

YMMV, but you can try using the Array.IndexOf method like so..

foreach (FileInfo file in fiImport

DoSomething(file)
statusBar.Text = string.Format("Processing {0} of {1}", Array.IndexOf(fiImport, file), fiImport.Length)


I say your mileage may vary because this returns the index of the first item found that matches and if the same FileInfo object was in the array in multiple slots then this wouldn't work. The IndexOf method can accept a starting index for the search but then you're back where you started. In addition, the IndexOf method is going to be scanning the array each time looking for the object; performance-wise you are going to be much better off keeping your separate index

For what it's worth, though, I tend to go back to using the "classic" for-loop whenever I hit situations that complicate the foreach scenario

-- T
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top