I noticed some strange things when I was working on deleting list items. There is no direct way of clearing out the list item collection. You have to loop through the collection and delete item by item. No big deal, all it takes is the below piece of code:
//Delete List items
for (int i = 0; i < list.Items.Count; i++)
{
list.Items[i].Delete();
}
Since it was a happy coding day I hit F5 without any problems. But, it hits me back with "Specified argument was out of the range of valid values" to spoil my day. I went to my list and noticed that it deleted the alternate items in the list! So what happened? After deleting the 0th item, item collection got updated and all the items were moved up. That explains why only the alternate items were deleted. Simple to fix, thought I could do it in couple of ways: always delete the 0th item in the collection or loop in the reverse order and delete the ith item, so did this:
//Delete List items
for (int i = 0; i < list.Items.Count; i++)
{
list.Items[0].Delete();
}
F5 again, no errors, everybody should be happy. I go to my list to see items still not deleted! So, made a little change, used list.ItemCount instead of list.Items.Count and tried this for fun:
//Delete List items
for (int i = 0; i < list.ItemCount; i++)
{
list.Items[0].Delete();
Console.WriteLine(list.Items.Count.ToString());
}
Console.WriteLine(list.ItemCount.ToString());
The output statement inside the loop prints out the updated list count and the one outside still gives the original count! Now you know the difference between the two.