2011-04-14 280 views
0

我想插入产品详情数组列表中的产品的ArrayList数组列表存储到在c#另一个数组列表

ArrayList的产品=新的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充满了最后的产品详细的ArrayList。 我在这里做什么错?

+0

什么'myTable.Rows.IndexOf(myRow )每次迭代返回? – khachik 2011-04-14 11:40:55

+0

它返回foreach循环的索引。 – 2011-04-14 11:41:36

+0

你想添加ArrayList作为一个整体还是其最后一个项目?你可以更清楚你正在试图做 – w69rdy 2011-04-14 11:41:58

回答

1

尝试移动

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是不要每次都复制你的清单...

1

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

但仍然,产品中的所有条目将包含相同的东西... – 2011-04-14 11:45:26

相关问题