By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,467 Members | 1,605 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,467 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.
Nov 15 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
TB

----- 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

Nov 15 '05 #2

P: n/a
Robert,

You may want to read

http://weblogs.asp.net/ericgu/archiv.../28/63957.aspx

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 15 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.