Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate a sharepoint list

Tags:

c#

sharepoint

In code how can I access a list e.g "MyList" in sharepoint, then iterate through this list items and get the value of a particular column on that list e.g the "URL" column?

like image 641
raklos Avatar asked Jun 08 '09 16:06

raklos


2 Answers

To retrieve all items from a list and iterate through each one, the best solution would be as follows (assuming that this code is run as part of a feature):

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    using(SPSite site = properties.Feature.Parent as SPSite)
    {
        SPList list = site.RootWeb.Lists["ListName"];
        SPListItemCollection items = list.Items;

        foreach (SPListItem listItem in items)
        {
            Response.Write(SPEncode.HtmlEncode(listItem["Url"].ToString()) +"<BR>");
        }
    }
}

But if the list is very large, it would be better to paginate through the list items:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    using(SPSite site = properties.Feature.Parent as SPSite)
    {
        SPList list = site.RootWeb.Lists["ListName"];

        if(items.ItemCount > 100)
        {        
            SPQuery query = new SPQuery();
            query.RowLimit = 100;
            int index = 1;

            do
            {
                SPListItemCollection items = list.GetItems(query);

                foreach (SPListItem listItem in items)
                {
                    Response.Write(SPEncode.HtmlEncode(listItem["Url"].ToString()) +"<BR>");
                }

                query.ListItemCollectionPosition = items.ListItemCollectionPosition;
                index++;

            } while (query.ListItemCollectionPosition != null);
        }
        else
        {
            SPListItemCollection items = list.Items;

            foreach (SPListItem listItem in items)
            {
                Response.Write(SPEncode.HtmlEncode(listItem["Url"].ToString()) +"<BR>");
            }
        }
    }
}

This is based on the Microsoft's Best Practices for SharePoint.

like image 170
Tangiest Avatar answered Oct 12 '22 23:10

Tangiest


From this blog post:

The correct way to do it is to store the Items property return value in a SPListItemCollection variable. With this the database is only queried once and we will then iterate over the result set that is stored within the collection object. Here is the changed sample code:

SPListItemCollection items = SPContext.Current.List.Items;
for(int i=0;i<100 && i<items.Count;i++) {
  SPListItem listItem = items[i];
  htmlWriter.Write(listItem["Title"]);
}
like image 20
Greg Hurlman Avatar answered Oct 12 '22 23:10

Greg Hurlman