2013-03-18 98 views
1

我正在尋找更好的數據結構或方法來簡單替換動態數組中的對象。似乎列表是選擇,但是我閱讀並注意到RemoveAt和Insert的性能不如我所希望的那麼好。替代RemoveAt並插入列表項目

讓我解釋什麼,我想實現:

列表1

  1. 清單項目1
  2. 列表項2
  3. 列表項3

列表2

  1. 列表項1
  2. 列表項2

兩個列表使用相同的對象類型。我想用List1 [1] - List item 1 clone來替換List2的空列表項。我使用克隆,因此複製的列表項的值是一個單獨的實例。

我也想用列表2的列表項1的克隆替換列表2的列表項2。

這裏是什麼,我想實現一些示例代碼:

projCraneVertices.RemoveAt(projCraneVertices.Count - 4); 
projCraneVertices.Insert((projCraneVertices.Count - 3), realCraneVertices[botPoint].clone()); 
projCraneVertices.RemoveAt(projCraneVertices.Count - 3); 
projCraneVertices.Insert((projCraneVertices.Count - 2), projCraneVertices[botPoint].clone()); 
projCraneVertices.RemoveAt(projCraneVertices.Count - 2); 
projCraneVertices.Insert((projCraneVertices.Count - 1), realCraneVertices[topPoint].clone()); 
projCraneVertices.RemoveAt(projCraneVertices.Count - 1); 
projCraneVertices.Insert((projCraneVertices.Count), projCraneVertices[topPoint].clone()); 

回答

0

我也想用列表2列表項 1的克隆來替換列表2列表2項。

那麼,你可以做簡單的是這樣的:使用的T名單將解決你RemoveAt移除的問題和插圖本使用引擎蓋下陣,並會揭露一些很好的功能,你

proCraneVertices[2] = realCraneVertices[1].Clone(); 
+0

我想應該是這樣簡單。我在沒有克隆功能的情況下嘗試過類似於此的操作,但它不能按預期工作。謝謝。 – 2013-03-18 14:33:18

0

從我能理解,你想有一個Replace方法。試試這個擴展:

public static class Extensions 
{ 
    public static void Replace<T>(this IList<T> list, int index, T item) 
    { 
    list[index] = item; 
    } 
} 

調用,比如:

List<int> ints = new List<int>() { 1, 2, 3 }; 
    List<int> ints2 = new List<int>() { 4, 5, 6 }; 
    ints.Replace(0, ints2[0]); 

以上將使第一個列表 - 4, 2, 3

0

將有助於擺脫這些厭煩的方法。

您可以使用List提供的一些功能,如下所示。

更換// Replact的項目從一個項目到另一個項目

List of T Class