开发者

Storing arraylist into another arraylist in c#

开发者 https://www.devze.com 2023-02-26 03:07 出处:网络
I want to insert productDetailarraylist in products arraylist ArrayList products = new ArrayList(); ArrayList productDetail = new ArrayList();

I want to insert productDetail arraylist in products arraylist

ArrayList products = new ArrayList();

ArrayList productDetail = new ArrayList();

   foreach (DataRow myRow in myTable.Rows)
   开发者_JS百科  {
     productDetail.Clear();                      
      productDetail.Add( "CostPrice" + "," + myRow["CostPrice"].ToString());

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

But each entery in product list is filled with last productdetails ArrayList. What wrong I am doing here?


Try moving

ArrayList productDetail = new ArrayList();

inside the foreach loop:

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);
}

The point is that, in your code, you are always adding a reference to the same object: Insert is not making a copy of your list each time...


productDetails only ever has one item in it. Your first step is productDetail.Clear(); Move that outside the foreach to achieve your desired result.

    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);
         }
0

精彩评论

暂无评论...
验证码 换一张
取 消