Read next in foreach ( string s in myArray )

  • Thread starter Thread starter Arjen
  • Start date Start date
A

Arjen

Hello,

I have a this:
foreach ( string s in myArray ) {

if ( s == ""test") {
}

}

How can I read the next "s" (if there is a next one) inside the current
readed "s"?

Thanks!
Arjen
 
Hello,

I have a this:
foreach ( string s in myArray ) {

if ( s == ""test") {
}

}

How can I read the next "s" (if there is a next one) inside the current
readed "s"?

Thanks!
Arjen

A foreach loop is designed to loop through a collection and only
expose one item in the collection at a time. What you can do, is
change the logic in something like this:

string[] arrItems = new string[5];
arrItems[0] = "test0";
arrItems[1] = "test1";
arrItems[2] = "test2";
arrItems[3] = "test3";
arrItems[4] = "test4";

string strPrevious = null;
foreach (string str in arrItems)
{
if (strPrevious != null)
{
// strPrevious is the previous item
// str is the current item
}
strPrevious = str;
}
 
Thanks for your answer but I need to look forward.
I don't care if it is a while, for each, etc. statement.

But I need to read one item forward.
I also want to check if there is a next item.

Arjen




L# said:
Hello,

I have a this:
foreach ( string s in myArray ) {

if ( s == ""test") {
}

}

How can I read the next "s" (if there is a next one) inside the current
readed "s"?

Thanks!
Arjen

A foreach loop is designed to loop through a collection and only
expose one item in the collection at a time. What you can do, is
change the logic in something like this:

string[] arrItems = new string[5];
arrItems[0] = "test0";
arrItems[1] = "test1";
arrItems[2] = "test2";
arrItems[3] = "test3";
arrItems[4] = "test4";

string strPrevious = null;
foreach (string str in arrItems)
{
if (strPrevious != null)
{
// strPrevious is the previous item
// str is the current item
}
strPrevious = str;
}
 
Thanks for your answer but I need to look forward.
I don't care if it is a while, for each, etc. statement.

But I need to read one item forward.
I also want to check if there is a next item.

Arjen

In fact, you are looking forward. The second time you loop, you have
the previous item and the current item. So in fact you are looking
forward, because the first item is strPrevious and the next item is
str. So use strPrevious as the current item and str as the next item.
 
Addendum:

it may be easier to use a normal for loop:

for (int i=0; i<arrItems.Length; i++)
{
string strCurrentItem = arrItems;
if (i < arrItems.Length-1)
{
string strNextItem = arrItems[i+1];
}
}
 
Yes, the last one I will use.
Thanks!

Arjen


L# said:
Addendum:

it may be easier to use a normal for loop:

for (int i=0; i<arrItems.Length; i++)
{
string strCurrentItem = arrItems;
if (i < arrItems.Length-1)
{
string strNextItem = arrItems[i+1];
}
}
 
Back
Top