1

is this a correct way to move objects from one list to another?

private ObservableCollection<SomeObject> toBeProcessed = 
                                new ObservableCollection<SomeObject>();


public ObservableCollection<SomeObject> ToBeProcessed 
{
    get
    {
        return toBeProcessed ;
    }
    set
    {
        //implements INotifyProperyChanged:
        SetField(ref toBeProcessed , value, "ToBeProcessed"); 
    }
}


public void MoveSelected(ObservableCollection<SomeOject> SelectedObjects)
{
    foreach (var obj in SelectedObjects)
    {
        ToBeProcessed.Add(obj);
        SelectedObjects.Remove(obj);
    }
}

is this the right way? if yes, is there a better way?

Update, sorry figured that it cant be done in a foreach loop so change it to this

for (int i = SelectedObjects.Count - 1; i >= 0; i--)
{
    ToBeProcessed.Add(SelectedObjects[i]);
    SelectedObjects.RemoveAt(i);
}

is it still the right way?

FPGA
  • 3,525
  • 10
  • 44
  • 73

2 Answers2

2

Well, you could simply do:

foreach (var obj in SelectedObjects)
    ToBeProcessed.Add(obj);

SelectedObjects.ClearItems();
sloth
  • 99,095
  • 21
  • 171
  • 219
1

You cannot modify a collection when you go through it no matter with index or foreach. However, from your description, SelectedObjects here behaves more like a "temporary collection", which is selected from another collection of ToSelectObjects, so you may not need to remove objects from it, but after adding them into ToBeProcessed, foreach loop SelectedObjects again and remove them from ToSelectObjects...

slepox
  • 792
  • 4
  • 9