0

I have a variable var1 which is a customized class that contains a single list of strings. I have another variable var2 which is a list of classes like var1.

What I am aiming to do is I need to iterate over var2, class by class and instantiate AddRange to combine var1s list of string with var2's ith class's own list of string. This is done independently, meaning that var1's list of strings stays the same at each iteration. Only at each iteration will its list of string be combined with that of var2's list of string, but after this iteration, it must revert back to the original. The problem is that I cant get this to work. Each time i add an string, it doesn't revert back.

I've tried making a deep copy and at the end of each iteration setting the intermediate clone class to null. Any ideas?

Below is a rough "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");

}
user1234440
  • 22,521
  • 18
  • 61
  • 103

2 Answers2

0

So, var1 must be unchanged. Either combine the strings into the other var1, or if that one must too be left as is, use a new list all together. I see no need to bother with cloning.

Gabriel Negut
  • 13,860
  • 4
  • 38
  • 45
0

So, you basically have to concatenate two lists of strings in a single string without touching the strings themselves.

Would something like this do for you?

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

Aggregate iterates over an IEnumerable and returns the concatenation of all its items.

fogbanksy
  • 494
  • 4
  • 7