0

hi i already had a similar problem but unfortunately i can't figure it out how to solve it. I have a List<int> tmpList and a List<int> tmpSpeicherListe where i want to copy my tmpList so i can edit my tmpList and reset it when i need to.

I want to edit tmpList multiple times in for loop and reset it everytime while loop repeats but if i remove one value of tmpList at position x it removes the value of tmpSpeicherListe at position x too. So where should i place the declaration of List<int> tmpSpeicherListe = tmpList; or where else is the mistake?

ps: this is just a part of my code

//...

List<int> tmpSpeicherListe = tmpList;            //copy tmpList
int basisPosition = 2;
int counter2 = 0;

while(counter2 + 2 < tmpList.Count - 1)
{
    basis = tmpList[basisPosition];
    for (int m = 1; m < tmpList.Count - basisPosition; m++)
    {
        int speicher = tmpList[basisPosition + m];
        bool vorhanden = false;
        for (int n = 0; n < intKombinierbar[basis].Length; n++)
        {
            if (intKombinierbar[basis][n] == speicher)
            {
                vorhanden = true;
                break;
            }
        }
        if(vorhanden == false)
        {
            tmpList.RemoveAt(basisPosition + m);        //edit tmpList BUT tmpSpeicherListe changes too
        }
    }


    if(tmpList.Count <= i)
    {
        tmpList = tmpSpeicherListe;            //reset tmpList
        counter2++;
        basisPosition = 2 + counter2;
                                                
    }
    else if (basisPosition == tmpList.Count - 2)
    {
        großeKombinationen.Add(tmpList);
        tmpList = tmpSpeicherListe;            //reset tmpList
        counter2++;
        basisPosition = 2 + counter2;
                                                
    }
    else
    {
        basisPosition++;
    }
}
//...
MaDrexan2
  • 9
  • 2

1 Answers1

0

You should clone List. You set reference of tmpSpeicherListe to reference of tmpList. You can clone like this.

List<int> tmpSpeicherListe = new List<int>(tmpList);
Mustafa Arslan
  • 774
  • 5
  • 13
  • If you plan on removing objects from the `tmpList` it will also remove them from the `tmpSpeicherListe` as well using this approach. – Trevor Sep 30 '20 at 13:29