动态加载list的值不正确

cherish_55 2013-04-26 03:19:37
动态加值到list<string[]>中,

List<string[]> Info = new List<string[]>();
int iRowsCount = 0;
if (dt.Rows.Count > 0)
iRowsCount = dt.Rows.Count;

string[] tmpInfo = new string[2];
if (iRowsCount>0)
{
for (int i = 0; i < iRowsCount; i++)
{
tmpInfo[0] = dt.Rows[i][0].ToString();
tmpInfo[1] = dt.Rows[i][1].ToString();
Info.Add(tmpInfo);
}
}

这段代码执行后,Info里的值为什么只保存了最后一条记录:info{{"2","tst2"},{"2","tst2"}}
dt的数据是
1 tst1
2 tst2
这是为什么呢?
...全文
49 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
cherish_55 2013-04-26
  • 打赏
  • 举报
回复
正解。虽然没有每次重新定义变量,但是每次都重新赋值了,而且是赋一次值,就加到list里啊,为什么还会把值冲掉
_老吴 2013-04-26
  • 打赏
  • 举报
回复

 List<string[]> Info = new List<string[]>();
 if(dt!=null&&dt.Rows.Count>0)
{    
    foreach (DataRow dr in dt.Rows)
    {
        string[] tmpInfo = new string[2];
        tmpInfo[0] = dr[0].ToString();
        tmpInfo[1] = dr[1].ToString();
        Info.Add(tmpInfo);
    }
}
            
victo7 2013-04-26
  • 打赏
  • 举报
回复

 List<string[]> Info = new List<string[]>();
            int iRowsCount = 0;
             if (dt.Rows.Count > 0)
                iRowsCount = dt.Rows.Count;
 
                       if (iRowsCount>0)
            {              
                for (int i = 0; i < iRowsCount; i++)
                {

                    string[] tmpInfo = new string[2];

                    tmpInfo[0] = dt.Rows[i][0].ToString();
                    tmpInfo[1] = dt.Rows[i][1].ToString();
                    Info.Add(tmpInfo);
                }
            }

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧