Tuesday, 11 December 2007

ItemCount and Items.Count

Noticed a strange thing the other day, a list has the property ItemCount and also an Items collection which has its own .Count but they don't always give the same answer. If I have a piece of code like this pointing to a list with 4 items in it.

1 using (SPSite site = new SPSite("http://mwmoss/marktest"))
2 {
3 using (SPWeb web = site.OpenWeb())
4 {
5 SPList list = web.Lists["Mark's Contacts"];
6
7 while(list.Items.Count > 0)
8 {
9 list.Items[0].Delete();
10 Console.WriteLine("ItemCount " + list.ItemCount.ToString());
11 Console.WriteLine("Items.Count " + list.Items.Count.ToString());
12 }
13 }
14 }


The output looks like this:-

ItemCount 4
Items.Count 3
ItemCount 4
Items.Count 2
ItemCount 4
Items.Count 1
ItemCount 4
Items.Count 0

I guess internally some collection isn't getting updated as we go round the loop. Something to be careful of anyway.

3 comments:

Matt Taylor said...

Hi Mark

I wonder if ItemCount is only updated when the Update method of the SPList instance is invoked? Certainly a demonstration of the inconsistences that we contend with throughout the SharePoint OMs.

Matt

PS hope you and Chris are keeping well.

iPear Carer said...

Hi Mark,

I came accross this very point this week. Matt is correct, the items appears to the items of the copy of the data, where ItemCount is referring to the actual data. I am guessing the "items" are a data set (See the lists function GetDataSet)

Once the changes are committed, using item.Update() then the ItemCount property changes.

Anonymous said...

I recently ran into this issue and through walking through the process several times discovered that the discrepancy between the counts was because the user that was being used did not have sufficient rights to the list. Once I gave the user more permissions to the list both counts matched up