I have a string array, and a for each loop. I want to loop through the array and do something to each field and then output the result of each field to a new variable.
EDIT: Each field of the array gets a value from a hidden field that represents a time in mins. In the foreach loop, it was my intention to convert each of the fields from mins to HH:mm format. Then I need to pass the new format into a new variable.
Array:
string[] field = new string[8];
field[0] = field_0_0.Value;
field[1] = field_0_1.Value;
field[2] = field_0_2.Value;
field[3] = field_0_3.Value;
field[4] = field_1_0.Value;
field[5] = field_1_1.Value;
field[6] = field_1_2.Value;
field[7] = field_1_3.Value;
Foreach Loop:
foreach (string newfields in field)
{
//Do something to each field
}
The part I am looking for assistance with is assigning each result to a new variable. Can anybody point me in the right direction, or even suggest a different/better way to do this.
Thanks in advance.
Just use an ordinary for
loop.
for(int i=0;i<field.Length;i++) {
string curValue = field[i];
// do something with curValue, change it in some way
field[i] = curValue; //update
}
If this is not what you're asking for, please clarify.
You can change the object your are enumerating, but not with a foreach. You will need to use for loop. Modified sample thanks to comments
List<string> mylist = new List<string>();
mylist.Add("item1");
mylist.Add("item2");
for (int i = 0; i < mylist.Count; i++)
{
mylist[i] = mylist[i].Replace("i", "o");
}
Use for
instead foreach
, the foreach
don't let you change your values.
Use a for
like this one:
for(int i = 0; i < field.Length; i++)
//Do something to each field
field[i] = "text"+i;
long i = 0;
foreach(string field in fields){
// Use i counter to initialize the array index
fields[i]="New Field String.";
// Increment the counter i by 1
i++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.