【问题标题】:Storing arraylist into another arraylist in c#在c#中将arraylist存储到另一个arraylist中
【发布时间】:2011-04-14 11:35:59
【问题描述】:

我想在产品数组列表中插入 productDetail 数组列表

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

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

【问题讨论】:

  • myTable.Rows.IndexOf(myRow) 在每次迭代中返回什么?
  • 它返回foreach循环的索引。
  • 您想将 ArrayList 作为一个整体添加还是添加最后一项?您能更清楚地说明您正在尝试做的事情吗
  • 试试products.Add((object)productDetail); 而不是Insert
  • ArrayList 已被弃用,如果可以避免,则不应真正使用它。泛型在这里很有用,尤其是 List.

标签: c# list arraylist


【解决方案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 并不是每次都复制您的列表...

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 2013-05-19
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 2020-11-29
      • 2018-08-19
      相关资源
      最近更新 更多