2011-04-28 23 views
0

有可能将两个arraylist中的数据存入<list>ArrayList操作?

这里是我的代码有两个数组,将合并:

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

我认为与第三'arrPrices'你的意思'arrDetails',是吧? – Bastardo 2011-04-28 07:53:30

回答

3

您可以使用LINQ仅仅做到这一点:

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

CastIEnumerable

1

如果你想从arrPrices值移到lstStockInfoPricelstStockInfoDetails,你可以遍历数组列表,把列表中的元素。像这样:

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

这是可能的。

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

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

我这个实用工具类不是你自己的,那么你坚持与马吕斯的答案。但是,如果您控制该Util类,则可以使GetPrices和GetDetails方法分别返回类型IEnumerable和IEnumerable。

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

另外,您在arrPrices声明中的分配是浪费时间 - 分配的对象从未被使用,并且会被垃圾收集。

你GetPrices()方法返回一个ArrayList - 即的ArrayList和

arrPrices = oUtils.GetPrices(SymbolIndex); 

只是使arrPrices指的是新的列表。那么当你声明arrPrices时没有引用你分配的引用,所以它被抛弃了。

像这样做: -

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