Skip to main content
 首页 » 编程设计

c#之foreach 循环在这里到底在做什么......帮助我准确地理解它

2024年02月05日13wuhuacong

Can anybody help me understand what these lines of codes really means...i understand it but not exactly...i mean what foreach is exactly doing here???

if (dt.Rows.Count > 0) 
    { 
        //GridView1.Visible = true; 
        Gridview1.DataSource = dt; 
        Gridview1.DataBind(); 
        StringBuilder sb = new StringBuilder(); 
 
        foreach (DataColumn col in dt.Columns) 
        { 
            sb.Append(col.ColumnName + ","); 
        } 
 
        sb.Remove(sb.Length - 1, 1); 
        sb.Append(Environment.NewLine); 
 
        foreach (DataRow row in dt.Rows) 
        { 
            for (int i = 0; i < dt.Columns.Count; i++) 
            { 
                sb.Append(row[i].ToString() + ","); 
            } 
 
            sb.Append(Environment.NewLine); 
        } 
 
        Response.ClearHeaders(); 
        Response.AppendHeader("Content-Disposition", "attachment; filename=CDR OF " + TextBox1.Text + ".csv"); 
        Response.AppendHeader("Content-Length", sb.Length.ToString()); 
        Response.ContentType = "text/csv"; 
        Response.Write(sb.ToString()); 
        Response.Flush(); 
        Response.End(); 
    } 
    else 
    { 
        //GridView1.Visible = false; 
        Show("No CDR Found!"); 
    } 

And can we use StringWriter or string in place of StringBuilder ???

请您参考如下方法:

  1. 第一个循环用逗号列出所有列名:

colname1,colname2,colname3,

  1. Remove 然后删除最后一个逗号并添加一个换行符

colname1,colname2,colname3\n

  1. 第二个循环列出每一行每一列的所有值

colname1,colname2,colname3\n row1col1value,row1col2value,row1col3value,\n -- 注意这里的逗号没有被删除 row2col1value,row2col2value,row2col3value,\n row3col1value,row3col2value,row3col3value,\n row4col1val 等...

是的,我认为您可以使用字符串而不是字符串生成器。