Home > Mobile >  How can i transfer objects from a list to another list?
How can i transfer objects from a list to another list?

Time:11-10

How can i move 3 items from list a to list b, removing those elements from list a at the same time

 for (int i = 0; i < NeedToClean.Count; i  )
 {
     if (!Cleaing.Contains(NeedToClean[i]) && Cleaing.Count != 3)
     {
         Cleaing.Add(NeedToClean[i]);

         break;
     }
     else
     {
         NeedToClean.Remove(Cleaing[i]);
     }
}

CodePudding user response:

I don't know if it can help you, but with the take you can take the first n items of a list, in this way you can copy them and then delete them, in the example below I created a list with 4 elements, I took the first 3 I moved them to empty list and subsequently deleted.

var a = new List<string>() { "Alpha", "Beta", "Gamma", "Delta" };
var b = new List<string>();

b.AddRange(a.Take(3));
a.RemoveRange(0, 3);

CodePudding user response:

You can remove items from a list that you're iterating over if you iterate (and remove) from the end. This way your index variable is always in range.

for (int i = NeedToClean.Count - 1; i >= 0; i--)
{
    if (!Cleaing.Contains(NeedToClean[i]))
    {
        // Add the item to one array
        Cleaing.Add(NeedToClean[i]);

        // Remove it from the original array
        NeedToClean.RemoveAt(i);

        // Quit when we've moved 3 items
        if (Cleaning.Count == 3) break;
    }
}

CodePudding user response:

List indexes;
for (int i = 0; i < NeedToClean.Count; i  )
{
    if(!Cleaing.Contains(NeedToClean[i]) && Cleaing.Count != 3)
    {
        Cleaing.Add(NeedToClean[i]);
        indexes.Add(i);
    }
}
while(indexes.Length != 0)
{
    int biggest;
    foreach(int i in indexes){
        biggest = (i > biggest) ? i : biggest;
    }
    NeedToClean.Remove(Cleaing[biggest]);
}

Now, this may be a bit overcomlicated, and I am not really confortable in cpp, but something like this should work. (Coming form C#)

The reason of that while loop is that we remove indexes from the end of the list/array first, so things don't conflict. Hope it helps and my reputation won't get stomped into the ground :D

  •  Tags:  
  • c#
  • Related