Renê Lima
Renê Lima

Reputation: 27

store all the results of a loop in a single string

I am trying to store the resulting strings together (combine them) into a single string.

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

Upvotes: 1

Views: 803

Answers (2)

Chris Ray
Chris Ray

Reputation: 5003

Something like this with Linq might work:

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

Upvotes: 2

mgnoonan
mgnoonan

Reputation: 7200

I would use a StringBuilder for this rather than a 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();

Strings are immutable, so they cannot be changed. If you keep appending values to the same string, you may run into some performance problems creating and destroying the values all the time. StringBuilder will let you keep appending without all that overhead.

Upvotes: 5

Related Questions