Earlgray
Earlgray

Reputation: 647

WP7 - Delete multiple items Linq to XML

I need to delete all items from my XML file where node Finished != "" but my code delete only first item where this condition is true

My code:

try
{
    var file = IsolatedStorageFile.GetUserStoreForApplication();
    XElement xElem;

    using (IsolatedStorageFileStream read = file.OpenFile("tasks.xml", FileMode.Open))
    {
        xElem = XElement.Load(read);
    }

    var tasks = from task in xElem.Elements("Task")
                where (string)task.Element("Finished") != ""
                select task;

    using (IsolatedStorageFileStream write = file.CreateFile("tasks.xml"))
    {
        foreach (XElement task in tasks)
        {
            task.Remove();
        }

        xElem.Save(write);
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
finally
{
    NavigationService.GoBack();
}

But if I replace task.Remove(); by MessageBox it shows me message box multiple times as it is right.

What is wrong in my code?

Upvotes: 0

Views: 458

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125640

You should call ToList() when you search for items and then use that list as a source in foreach loop, instead of IEnumerable.

var tasks = (from task in xElem.Elements("Task")
             where (string)task.Element("Finished") != ""
             select task).ToList();

It's described on MSDN, within XNode.Remove method description:

In LINQ to XML programming, you should not manipulate or modify a set of nodes while you are querying for nodes in that set. In practical terms, this means that you should not iterate over a set of nodes and remove them. Instead, you should materialize them into a List by using the ToList extension method. Then, you can iterate over the list to remove the nodes. For more information, see Mixed Declarative Code/Imperative Code Bugs (C#) (LINQ to XML).

Upvotes: 2

Related Questions