# how to get the 3rd index in a foreach iteration c#

here is my code

string[] strData = {"P  ","B  ","P  ","PB ","P  ",P  "};
string OriginalData ="";
for(int i = 0; i < strData.Length; i++){
OriginalData += strData[i];
OriginalData += ",";
}
string[] newNewData = strData.Split(',');
//i want to get the 3rd index from inside the foreach
foreach(string newStrData in newNewData){
//display the 3rd index
}


What i did here was split my string so that i can parse them 1 by 1 later for my conditional statement . what i want here is that i want to get the 3rd index inside of my variable newStrData .

• Only the 3rd index or a range starting at the 3rd index? – Slagmoth May 10 '18 at 15:34
• yes sir for now the 3rd index only – Gin09 May 10 '18 at 15:40
• @slagmoth . ididnt yet accept an answer sir . – Gin09 May 10 '18 at 15:57

If you only have an IEnumerator and don't have an IList access, you can do this:

int i = 0;
foreach(string newStrData in newNewData)
{
i++;
if (i == 3)
{
//display the 3rd index
}
}


If you have IList access, use a for loop use the indexer as newNewData[2].

• how could i display the index sir – Gin09 May 10 '18 at 15:46
• The i-1 is index here. – S. Tarık Çetin May 10 '18 at 15:47
• i dont get it how can i display it sir . haha sorry – Gin09 May 10 '18 at 15:50
• Debug.Log puts it in the console. – S. Tarık Çetin May 10 '18 at 15:50
• @Gin09 I am glad I could help but you should try to understand the algorithm behind what is going on rather than looking for ready-made code. It will help you better in the long run. – S. Tarık Çetin May 10 '18 at 16:04

Simply put: you can't. The concept of an index it's foreign to Enumerators.

If you need an index, use a for loop instead, i.e.:

for (int i = 0; i < newNewData.Length; i++) {
if (i == 2) {
// Operate on newNewData[i]
}
}


Note that the for loop is useless if you only need to do something with the third element of the array and nothing else with the others, of course, you can just access that third element directly with newNewData[2].

• i cant do it like this for(int i=0;i<newStrData.Length;i++){ if(i == 3) } – Gin09 May 10 '18 at 15:43

In regular C# you a string is simply a char[] therefore you can do the following:

int index = 2;

char x = newStrData[index];

string x = (string)newStrData[index];

Debug.Log(\$"The item at the 3rd index is : {newStrData[index]}");


I honestly don't know which version of C# Unity uses but if it uses string interpolation you can do that without casting to string if you need to log it. Concatenation is typically frowned upon due to the immutability of strings and their memory cost if done a lot.

If it doesn't support interpolation you can do this to avoid concatenation:

Debug.Log(string.Format"The item at the 3rd index is : {0}", newStrData[index]);


Collections are zero-based for C# as well so to get the 3rd one in a collection you would need to get index 2.

If you wanted a range starting at a given index could use Substring();