添加到列表的新项目覆盖前一个项目

时间:2015-07-16 18:22:43

标签: c# asp.net list

我在C#中使用List。我想在abc中添加值。但问题是第一个项目成功添加,但是当第二个项目将相同的值ovverride插入第一个项目时,示例第一个项目xyz成功插入,但当第二个项目abc来到它时,它是xyzxyz,两个项目都显示DataTable dtbl3 = new DataTable(); List<CartItems> lst = (List<CartItems>)Session["mycart"]; dtbl3 = DAL.Get("Select * from mytable"); List<EmailClass> lstCstmer = new List<EmailClass>(); for (int j = 0; j < lst.Count; j++) { emailLst.__EmailcstName = dtbl3.Rows[0]["cstm_name"].ToString(); emailLst.__EmailcstLName = dtbl3.Rows[0]["cstm_LName"].ToString(); emailLst.__EmailcstAddress = dtbl3.Rows[0]["cstm_Addr"].ToString(); emailLst.__EmailcstPhoneNo = dtbl3.Rows[0]["cstm_Phone"].ToString(); emailLst.__EmailcstCellNo = dtbl3.Rows[0]["cstm_CellNo"].ToString(); emailLst.__EmailcstskypId = dtbl3.Rows[0]["cstm_skypeId"].ToString(); emailLst.__EmailcstEmail = dtbl3.Rows[0]["cstm_email"].ToString(); emailLst.__EmailcstCountry = dtbl3.Rows[0]["cstm_country"].ToString(); emailLst.__EmailcstCity = dtbl3.Rows[0]["cstm_City"].ToString(); emailLst.__EmailcstZipcode =Convert.ToInt32( dtbl3.Rows[0]["cstm_ZipCode"].ToString()); emailLst.__EmailcstRemarks = dtbl3.Rows[0]["cstm_remarks"].ToString(); emailLst._EmailCartProdName = lst[j]._CartProdName; emailLst._EmailCartProdPrice = lst[j]._CartProdPrice; emailLst._EmailCartProdQnty = lst[j]._CartProdQnty; emailLst._EmailCartProdCode = lst[j]._CartProdName; emailLst._EmailTotalProdPrice = lst[j]._TotalProdPrice; lstCstmer.Add(emailLst); } 。这是我的代码。

var fortunes = ['a','b','c'];
app.get('/about', function(req, res){
    var temp = fortunes[Math.floor(Math.random()*Math.length)];
    res.render('about',{fortune:temp});
});

1 个答案:

答案 0 :(得分:2)

您反复添加相同的项目,并且因为它是引用类型,所以列表中的所有条目都指向EmailClass的同一个实例。

在每次循环迭代中创建一个新实例来修复它:

for (int j = 0; j < lst.Count; j++)
{
    emailLst = new EmailClass();

    emailLst.__EmailcstName = dtbl3.Rows[0]["cstm_name"].ToString();
    emailLst.__EmailcstLName = dtbl3.Rows[0]["cstm_LName"].ToString();
    emailLst.__EmailcstAddress = dtbl3.Rows[0]["cstm_Addr"].ToString();
    emailLst.__EmailcstPhoneNo = dtbl3.Rows[0]["cstm_Phone"].ToString();
    emailLst.__EmailcstCellNo = dtbl3.Rows[0]["cstm_CellNo"].ToString();
    emailLst.__EmailcstskypId = dtbl3.Rows[0]["cstm_skypeId"].ToString();
    emailLst.__EmailcstEmail = dtbl3.Rows[0]["cstm_email"].ToString();
    emailLst.__EmailcstCountry = dtbl3.Rows[0]["cstm_country"].ToString();
    emailLst.__EmailcstCity = dtbl3.Rows[0]["cstm_City"].ToString();
    emailLst.__EmailcstZipcode =Convert.ToInt32( dtbl3.Rows[0]["cstm_ZipCode"].ToString());
    emailLst.__EmailcstRemarks = dtbl3.Rows[0]["cstm_remarks"].ToString();

    emailLst._EmailCartProdName = lst[j]._CartProdName;
    emailLst._EmailCartProdPrice = lst[j]._CartProdPrice;
    emailLst._EmailCartProdQnty = lst[j]._CartProdQnty;
    emailLst._EmailCartProdCode = lst[j]._CartProdName;
    emailLst._EmailTotalProdPrice = lst[j]._TotalProdPrice;

    lstCstmer.Add(emailLst);

}