Index of object array

  • Thread starter Thread starter Spare Change
  • Start date Start date
S

Spare Change

Say I am iterating through an objects values:

int i;
DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
FileInfo[] rgFiles = di.GetFiles("*.aspx");
foreach(FileInfo fi in rgFiles)
htmlPgs[i++]=fi.Name;

What property of rgFiles could be substituted for i?
That is, can I write:
htmlPgs[rgFiles.<enumerator>];
instead?
How?
 
Spare Change said:
Say I am iterating through an objects values:

int i;
DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
FileInfo[] rgFiles = di.GetFiles("*.aspx");
foreach(FileInfo fi in rgFiles)
htmlPgs[i++]=fi.Name;

What property of rgFiles could be substituted for i?
That is, can I write:
htmlPgs[rgFiles.<enumerator>];
instead?

No: that's the main disadvantage of a foreach loop;

Internally the foreach loop queries the collection object for the
IEnumerable interface, gets an IEnumerator object from it, which only
exposes the methods "Current", "MoveNext", and "Reset": There's no way to
get an index from it, unless the object in question has some special
provisions for that (I know none that would).

I guess the main reason for this architecture is to ensure the foreach loop
can be used on any kind of collection: If you're iterating over a linked
list, database query keeping an index would be quite complex, as the
collection may change while it's iterated.

Niki
 
Spare Change said:
foreach(FileInfo fi in rgFiles)
htmlPgs[i++]=fi.Name;
What property of rgFiles could be substituted for i?
That is, can I write:
htmlPgs[rgFiles.<enumerator>];
instead?

When you need an index variable, use a regular for loop based on
Length or Count.

for (int i = 0; i < rgFiles.Length; i++)
{
// do something - this is the ith iteration
}

P.
 
I understand. But if I want to use the object type of the array, like the
FileInfo type, in the inside code. It just seems like a foreach is doing
some kind of enumeration, there must be a "selected" property, or
something, for the collection....

Spare Change said:
foreach(FileInfo fi in rgFiles)
htmlPgs[i++]=fi.Name;
What property of rgFiles could be substituted for i?
That is, can I write:
htmlPgs[rgFiles.<enumerator>];
instead?

When you need an index variable, use a regular for loop based on
Length or Count.

for (int i = 0; i < rgFiles.Length; i++)
{
// do something - this is the ith iteration
}

P.
 
The Devil said:
I understand. But if I want to use the object type of the array, like the
FileInfo type, in the inside code. It just seems like a foreach is doing
some kind of enumeration, there must be a "selected" property, or
something, for the collection....

If that was the case, you couldn't write code like this:

foreach (int x in samples)
foreach (int y in samples)
z += x*y;

which is of course perfectly legal.

Niki
 
Back
Top