简体   繁体   English

将数组的每个字段分配给变量,foreach 循环

[英]Assigning each field of an array to a variable, foreach loop

I have a string array, and a for each loop.我有一个字符串数组和一个 for 每个循环。 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.在 foreach 循环中,我打算将每个字段从 mins 转换为 HH:mm 格式。 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循环:

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循环。

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.您可以更改要枚举的对象,但不能使用 foreach。 You will need to use for loop.您将需要使用 for 循环。 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.使用for代替foreachforeach不允许您更改您的值。

Use a for like this one:像这样使用for

for(int i = 0; i < field.Length; i++)
   //Do something to each field 
   field[i] = "text"+i;
  1. Create variable counter and set it to zero.创建变量计数器并将其设置为零。
  2. long i = 0;
  3. Create the for each loop.创建 for 每个循环。
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++;
}
  1. This will assign a value to each of the fields array values这将为每个字段数组值分配一个值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM