Reputation: 8415
I want to remove user-selected elements from an XML list, using element indexes. For example:
foreach (int index in indexes)
{
Root.Descendants("book").ElementAt(index).Remove();
}
But this throws an IndexOutOfRangeException
. Any suggestions are appreciated.
Upvotes: 0
Views: 1358
Reputation: 107606
As you remove items, the number of remaining "book" elements (and their indices) changes. You might have 0, 1, 2, 3 in your indexes array, but once you remove the first item, your fourth index (3) is now out of range. If you indices are consecutive, you can reverse the order in which you remove the elements, so the current index can never be "out of range."
Try this:
for (int i = indexes.Length - 1; i >= 0; i--)
{
Root.Descendants("book").ElementAt(indexes[i]).Remove();
};
However, you mentioned that you want to remove "user-selected" elements, so I'm guessing your elements could be in a random order. Instead, you might want to try something like this:
IEnumerable<XElement> books = Root.Descendants("book");
IList<XElement> booksToRemove = new List<XElement>(indexes.Length);
foreach (int index in indexes)
{
booksToRemove.Add(books.ElementAt(index));
}
foreach (XElement book in booksToRemove)
{
book.Remove();
}
Now you don't have to care what order the elements or the indexes are in before removing them.
Upvotes: 4