繁体   English   中英

将arraylist存储到c#中的另一个arraylist中

[英]Storing arraylist into another arraylist in c#

我想在产品arraylist中插入productDetail arraylist

ArrayList products = new ArrayList();

ArrayList productDetail = new ArrayList();

  foreach (DataRow myRow in myTable.Rows) { productDetail.Clear(); productDetail.Add( "CostPrice" + "," + myRow["CostPrice"].ToString()); products.Insert(myTable.Rows.IndexOf(myRow),(object)productDetail); } 

但产品列表中的每个entery都填充了最后的productdetails ArrayList。 我在这做什么错?

productDetails只有一个项目。 你的第一步是productDetail.Clear(); 将它移到foreach之外以获得所需的结果。

    ArrayList products = new ArrayList();

    ArrayList productDetail = new ArrayList();

    productDetail.Clear(); 

       foreach (DataRow myRow in myTable.Rows)
         {

          productDetail.Add( "CostPrice" + "," + myRow["CostPrice"].ToString());

          products.Insert(myTable.Rows.IndexOf(myRow),(object)productDetail);
         }

试着移动

ArrayList productDetail = new ArrayList();

foreach循环中:

ArrayList products = new ArrayList();
foreach (DataRow myRow in myTable.Rows) {
    ArrayList productDetail = new ArrayList();
    productDetail.Add( "CostPrice" + "," + myRow["CostPrice"].ToString());
    products.Insert(myTable.Rows.IndexOf(myRow),(object)productDetail);
}

关键是,在您的代码中,您总是添加对同一对象的引用: Insert不会每次都复制您的列表...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM