【问题标题】:Get value in for loop to outside loop to array?在for循环中获取值到外部循环到数组?
【发布时间】:2017-12-11 08:24:45
【问题描述】:

这是我的代码。


          for (int i = 1; i < dataGridView2.RowCount - 1; i++)
                {

                    int valueCellIndex = 3;//assume calculate the 0th column
                    int resultCellIndex = 4;//assume result to put into the 1th column
                    var lastRow = dataGridView2.Rows[i - 1];
                    var curRow = dataGridView2.Rows[i];
                    double last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
                    double cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);

                    gain = Convert.ToInt32(curRow.Cells[resultCellIndex].Value = cur - last); //

                }
          JsonArray.Add(new JsonInput(close, gain));

如何让 for 循环中的“增益”进入 JsonArray ?

【问题讨论】:

  • 在for循环上方声明一个数组,并在for循环内的数组中添加元素

标签: c# for-loop datagridview


【解决方案1】:

由于gain变量是int类型,你可以创建一个List对象在循环内添加gain变量值。稍后将 int List 转换为 json 数组。

List<int> gainList = new List<int>();
for (int i = 1; i < dataGridView2.RowCount - 1; i++)
{

    int valueCellIndex = 3;//assume calculate the 0th column
    int resultCellIndex = 4;//assume result to put into the 1th column
    var lastRow = dataGridView2.Rows[i - 1];
    var curRow = dataGridView2.Rows[i];
    double last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
    double cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);    
    gain = Convert.ToInt32(curRow.Cells[resultCellIndex].Value = cur - last);
    gainList.Add(gain);
}

要将列表转换为 json 格式,您可以使用 System.Web.Script.Serialization 命名空间。

using System.Web.Script.Serialization;
.....
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(gainList);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 2021-07-01
    • 1970-01-01
    相关资源
    最近更新 更多