2011-04-28 25 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);