Categories
SharePoint

Looping through SPList items

Now this is something I’m guilty of time and time again. Within my PowerShell scripts I quite often query SharePoint lists and loop through them in the following way… What I should be doing is this…

Now this is something I’m guilty of time and time again. Within my PowerShell scripts I quite often query SharePoint lists and loop through them in the following way…

$site = New-Object Microsoft.SharePoint.SPSite( $url )
$web = $site.OpenWeb()
$list = $web.List

for ( $i = 0; $i < $list.Items.Count; $i++) {
   SPListItem listItem = activeList.Items[i];
   htmlWriter.Write(listItem["Title"]);
}

What I should be doing is this…

SPListItemCollection items = SPContext.Current.List.Items;

for(int i=0;i<100 && i<items.Count;i++) {
  SPListItem listItem = items[i];
  htmlWriter.Write(listItem["Title"]);
}