2015-04-04 60 views
0

我有一個變量var1,它是一個包含單個字符串列表的自定義類。我有另一個變量var2這是一個類似列表var1避免在C#中進行深度複製的解決方案

什麼,我的目標是什麼是我需要遍歷var2,按類類和實例AddRange串的var1s名單與var2i個類的自己的字符串列表結合起來。這是獨立完成的,這意味着var1的字符串列表在每次迭代中保持不變。只有在每次迭代時,其字符串列表纔會與var2的字符串列表相結合,但是在迭代之後,它必須恢復爲原始字符串。問題是我不能讓這個工作。每次我添加一個字符串,它都不會恢復。

我試過做一個深層複製,並在每次迭代結束時將中間克隆類設置爲null。有任何想法嗎?

下面是一個粗略的 「PeudoCode」

public void combineString(CustomClass var1) 
{ 
    // var2 is a class variable that contains a list of CustomClass 

    List<CustomClass> finalized = new List<CustomClass>(); 

    for (int i = 0; i < var2.Count; i++) 
    { 

      CustomClass tmpVar = (CustomClass)var1.Clone(); 
      tmpVar.addString(var2[i].StringSet); //each Custom class has a stringSet which is a list of strings 


      // .....Do some analysis of the strings of tmpVar 
      // if it passes the analysis add tmpVar in to finalize list 
      // none of the other components should change 

      if (pass analysis) 
      { 
       finalized.Add(tmpVar); 

      } 
      tmpVar = null; 

    } 

    // When the loop is done, the 'finalized' variable is a list of 
    // CustomClass but then each element inside finalized contains the same string set. 


    Console.WriteLine("Done"); 

} 
+0

發佈您的代碼? – 2015-04-04 15:54:29

+0

是的,我正在努力!抱歉! – user1234440 2015-04-04 15:56:47

+0

聽起來我可以使用*函數式編程來做到這一點。 – 2015-04-04 16:05:09

回答

0

所以,var1必須保持不變。要麼將這些字符串合併到另一個var1中,要麼必須將該字符串保留原樣,請一起使用新的列表。我看不到需要克隆。

+0

'var1'本身就是一個類,我需要它的組件保持完整無損。 – user1234440 2015-04-04 16:05:59

0

所以,你基本上必須在單個字符串中連接兩個字符串列表,而不必接觸字符串本身。

會這樣嗎?

string concatenated = var1.Concat(var2[i].StringSet).Aggregate((item1, item2) => item1 + item2);

Aggregate在一個IEnumerable迭代,並返回其所有項目的連接。