2009-11-12 17 views
8

嗨我試圖追加1列表到另一個。我已經使用它之前AddRange(),但它似乎沒有在這裏工作完成了...下面的代碼:不能將一個列表追加到C#中的另一個...嘗試使用AddRange

IList<E> resultCollection = ((IRepository<E, C>)this).SelectAll(columnName, maxId - startId + 1, startId);     
IList<E> resultCollection2 = ((IRepository<E, C>)this).SelectAll(columnName, endId - minId + 1, minId); 
resultCollection.ToList().AddRange(resultCollection2); 

我做了調試,檢查的結果,這是我的了:resultCollection具有計數4 resultCollection2的計數爲6,並且在添加該範圍後,resultCollection仍然只有4個計數,因此計數應爲10.

任何人都可以看到我在做什麼錯了嗎?任何幫助表示讚賞。

謝謝
馬特

回答

31

當你調用ToList()你是不是包裹在集合中List<T>您正在創建一個新的List<T>與它相同的項目。所以你在這裏有效地做的是創建一個新的列表,添加項目,然後扔掉列表。

你需要做這樣的事情:

List<E> merged = new List<E>(); 
merged.AddRange(resultCollection); 
merged.AddRange(resultCollection2); 

或者,如果您正在使用C#3.0,簡單地使用Concat,例如

resultCollection.Concat(resultCollection2); // and optionally .ToList() 
+0

太棒了,完美的工作,謝謝! – Matt 2009-11-12 19:26:34

4

我會假設.ToList()是創建一個新的集合。因此,您的物品將被添加到立即丟棄的新集合中,並且原始文檔不會被觸及。

+0

如果我試圖使它得到返回到一個新的列表它說。 「不能隱式地將類型'void'轉換爲'System.Collection.Generic.List '」,所以我的猜測是它沒有返回任何東西? – Matt 2009-11-12 19:16:37

+0

我犯了同樣的錯誤! AddRange返回void。 – 2009-11-12 19:18:19

+1

使用Greg Beech提供的解決方案。另外,如果接受他而不是我,我只是指出了問題,他已經完成了,並提供了一個解決方案! :) – Quibblesome 2009-11-12 19:18:22

1

resultCollection.ToList()將返回一個新的列表。

嘗試:

List<E> list = resultCollection.ToList(); 
list.AddRange(resultCollection2); 
+0

'AddRange'返回void。 – 2009-11-12 19:13:51

+0

斑點...固定。 – 2009-11-12 19:17:40

1

嘗試

IList的newList = resultCollection.ToList()的AddRange(resultCollection2);

List<E> newList = resultCollection.ToList(); 
newList.AddRange(resultCollection2); 
0

您可以使用任何的以下內容:

List<E> list = resultCollection as List<E>; 
if (list == null) 
    list = new List<E>(resultCollection); 
list.AddRange(resultCollection2); 

或者:

// Edit: this one could be done with LINQ, but there's no reason to limit 
//  yourself to .NET 3.5 when this is just as short. 
List<E> list = new List<E>(resultCollection); 
list.AddRange(resultCollection2); 

或者:

List<E> list = new List<E>(resultCollection.Concat(resultCollection2)); 
相關問題