【问题标题】:store all the results of a loop in a single string将循环的所有结果存储在单个字符串中
【发布时间】:2012-04-24 00:31:42
【问题描述】:

我正在尝试将生成的字符串一起存储(组合)成一个字符串。

for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    string pedido = dataGridView1.Rows[i].Cells[2].Value.ToString();
}

【问题讨论】:

    标签: c#


    【解决方案1】:

    我会为此使用StringBuilder 而不是String

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < dataGridView1.Rows.Count; ++i){
        sb.Append(dataGridView1.Rows[i].Cells[2].Value.ToString());
     }
    
    string pedido = sb.ToString();
    

    字符串是不可变的,因此无法更改。如果您一直将值附加到同一个字符串,则可能会一直在创建和销毁这些值时遇到一些性能问题。 StringBuilder 将让您继续追加而无需所有开销。

    【讨论】:

      【解决方案2】:

      这样的 Linq 可能会起作用:

      String.Join(",", (from a in dataGridView1.AsEnumerable() select a.Cells[2].Value.ToString()).ToList())
      

      【讨论】:

        猜你喜欢
        • 2023-02-07
        • 1970-01-01
        • 1970-01-01
        • 2015-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-31
        相关资源
        最近更新 更多