Skip to main content

Cloud

Difference between List.ItemCount and List.Items.Count

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Raja Ayyapusetty

Raja is a software consultant with over 9 years of experience in designing, developing and testing complex solutions using Microsoft technologies. Throughout his career he has worked primarily on SharePoint and .NET technologies. Raja has worked with SharePoint since the 2003 version and has deep understanding of its features and capabilities. Raja is also a certified Sitecore developer.

More from this Author

Follow Us
TwitterLinkedinFacebookYoutubeInstagram