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 }
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.
引用: