IList.Add()覆盖现有数据 [英] IList.Add() overwriting existing data

查看:110
本文介绍了IList.Add()覆盖现有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将数据添加到IList时遇到问题,但问题是每次我添加数据时,现有数据都会被当前代码覆盖,我的代码如下:

I'm facing a problem adding data to an IList but the problem is each time I added data the existing data is overwritten with the current one my code is given below:

Test test = new Test();
IList<Test> myList = new List<Test>();

foreach (DataRow dataRow in dataTable.Rows)
{
     test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
     test.LastName = dataRow.ItemArray[1].ToString();
     test.FirstName = dataRow.ItemArray[2].ToString();
     myList.Add(test);
}

这是什么原因?

推荐答案

在循环内移动测试对象的创建

move test object creation inside the loop

IList<Test> myList = new List<Test>();

foreach (DataRow dataRow in dataTable.Rows)
{   Test test =new Test();
    test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
    test.LastName = dataRow.ItemArray[1].ToString();
    test.FirstName = dataRow.ItemArray[2].ToString();
    myList.Add(test);
 }

您当前正在做的是在循环内更新test的同一时刻,并一次又一次地添加它..

what you currently doing is updating same instant of test inside the loop and add the same again and again..

这篇关于IList.Add()覆盖现有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆