1

I am looping through an ObservableCollection for items that have been marked by setting a boolean to true. After doing what I need with the item I want to remove it from the OnservableCollection. I can't do that within the foreach loop, so I was thinking of making a list of all the items marked, then after the foreach loop just clear all the items from the collection at once. But I can't even get started because I don't know how to get the index of the item in the foreach loop.

            private void Upload()
            {
                List<TestResult> kill;
                foreach (var tr in TestResults)
                {
                    if (tr.CanUpload)
                    {
                        StatusContent = "Uploading " + tr.FileName;
                        FileOps.UploadDocument(tr);
                        kill.Add(tr);
                        tr.CanUpload = false;
                        RaisePropertyChanged("TestResults");
                    }

                }
                //this doesn't work 
                //TestResults.Remove(TestResults.Where(x => x.CanUpload == true));
             }      

I've tried working with what I have above, but I am missing some critical pieces to make it work right.

ScottinTexas
  • 171
  • 1
  • 19

1 Answers1

2

Use a for loop instead. Like you noticed you can not remove items in a collection you are looping with a foreach.

But you have to update your current item index when removing items ;)

Something like this should do the work

for (var i = myList.Count() - 1; i >= 0; i--)
{
    ...
} 
Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
  • Thank you for your answer. I ended up with a foreach loop on a list created from the observable collection, then removed from the collection each item in the list that matched the criteria. – ScottinTexas Mar 17 '17 at 13:12
  • Your welcome. Would be nice when you accept and upvote it. – Mighty Badaboom Mar 17 '17 at 13:13