【问题标题】:ArrayList Manipulation?ArrayList 操作?
【发布时间】:2011-08-14 11:50:21
【问题描述】:

可以将两个arraylist中的数据存储到<list>中吗?

这是我的代码,其中包含两个将合并的数组:

ArrayList arrPrices = new ArrayList();
List<StockInfoPrice> lstStockInfoPrice = new List<StockInfoPrice>();
Util oUtils = new Util(); 
arrPrices = oUtils.GetPrices(SymbolIndex);

ArrayList arrDetails = new ArrayList();
List<StockInfoDetails> lstStockInfoDetails = new List<StockInfoDetails>();
Util oUtils = new Util(); 
arrPrices = oUtils.GetDetails(SymbolIndex);

【问题讨论】:

  • 我认为第三个arrPrices 是指arrDetails,嗯?

标签: c# casting arraylist


【解决方案1】:

你可以用 linq 简单地做到这一点:

lstStockInfoPrice.AddRange(arr1.Cast<StockInfoPrice>());
lstStockInfoPrice.AddRange(arr2.Cast<StockInfoPrice>());

IEnumerable 中查看Cast

【讨论】:

    【解决方案2】:

    有可能。

    如果 oUtils.GetPrices(SymbolIndex) 返回 StockInfoPrice,您可以尝试以下操作;

    lstStockInfoPrice.AddRange(oUtils.GetPrices(SymbolIndex));
    

    【讨论】:

      【解决方案3】:

      我这个 Util 类不是你自己的,那么你就会被 Marius 的回答所困扰。但是,如果您控制该 Util 类,则可以使 GetPrices 和 GetDetails 方法分别返回类型为 IEnumerable 和 IEnumerable 的某些内容。

      然后,您可以使用 List.AddRange() 方法将整个批次添加到另一个列表中。

      顺便说一句,您在 arrPrices 声明中的分配是浪费时间 - 分配的对象永远不会被使用,然后将受到垃圾回收的影响。

      您的 GetPrices() 方法返回一个 ArrayList - 即,一个 new arrayList,并且

      arrPrices = oUtils.GetPrices(SymbolIndex);
      

      只是让 arrPrices 引用新列表。然后没有引用您在声明 arrPrices 时分配的那个,所以它被丢弃了。

      这样做:-

      ArrayList arrPrices;
      List<StockInfoPrice> lstStockInfoPrice = new List<StockInfoPrice>();
      Util oUtils = new Util(); 
      arrPrices = oUtils.GetPrices(SymbolIndex);
      

      【讨论】:

        【解决方案4】:

        如果要将值从arrPrices 移动到lstStockInfoPricelstStockInfoDetails,您可以遍历数组列表并将元素放入列表中。像这样的:

        foreach(var o in arrPrices)
        {
          lstStockInfoPrice.Add(o); // or Add((StockInfoPrice)o)
        }
        

        【讨论】:

          猜你喜欢
          • 2021-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-24
          • 1970-01-01
          • 2023-01-25
          • 2021-11-04
          相关资源
          最近更新 更多