Working with List Objects and Collections

Applies to: SharePoint Foundation 2010

To perform actions on list data in a SharePoint Web site, you must first obtain an SPWeb object to serve as an entry point to the object model, allowing you to access lists, items, documents, users, alerts, and so on. For information about how to return SharePoint Web sites, see Getting References to Sites, Web Applications, and Other Key Objects.

Objects

Most classes in the Microsoft.SharePoint and Microsoft.SharePoint.Administration namespaces start with SP. Generally, classes in the Microsoft.SharePoint assembly that do not start with this prefix represent Web form controls.

SharePoint Foundation typically does not save modifications of object properties to the database until you call the Update method on the specified object. The following example shows how to change the title and description for the Tasks list.

         
Dim oList As SPList = oWebsite.Lists("Tasks")
oList.Title = "New_Title"
oList.Description = "List_Description"
oList.Update()
SPList oList = oWebsite.Lists["Tasks"];
oList.Title="New_Title";
oList.Description="List_Description";
oList.Update();

Note

Metadata for the document cannot be modified by using the Update() method of the SPListItem object if the document is checked out from a document library.

Collections

Just as lists are at the center of a SharePoint site, so are collections at the center of its object models. You can use each collection to add, delete, enumerate, and update a type of object. Collection classes generally share the following traits:

  • Have a name that ends in "Collection."

  • Implement the System.Collections.ICollection interface.

  • Have a Count property of type Int32.

  • Have an Int32 indexer that can be used to get the nth item in the collection.

  • Have an indexer that takes an item identifier.

  • Have Add and Delete methods.

Calling the Add method for a collection usually updates the database on the back-end server with the appropriate data, except when additional information is required in order to update data. In this case, using the Add method returns an object that you can use to gather the information. For example, to add an item to a list, first use the Add method of the Microsoft.SharePoint.SPListItemCollection class to return an SPListItem object, assign values to appropriate properties of the object, and then call the Update method to effect changes within the content database.

Indexers

Indexers provide a useful means to access individual items in collections. To return an item, use square brackets ([]) in Microsoft C# or parentheses (()) in Microsoft Visual Basic to contain either an index or a string that identifies the item within the collection.

For example, if oWebsite represents an instance of the SPWeb class, then SPList oList = oWebsite.Lists["Announcements"] returns the Announcements list in C#, while Dim oList As SPList = oWebsite.Lists("Announcements") returns the same list in Visual Basic.

To return items from the list, it is best practice to call one of the list object’s GetItem* methods and specify which items to retrieve. Using the Items property to get all the items in a list can diminish performance because it forces all columns for all items to be returned. Instead use, for example, the GetItems method and pass an SPQuery object to specify the subset: SPListItemCollection collItem = oList.GetItems(oQuery) (in Visual Basic, Dim collItem As SPListItemCollection = oList.GetItems(oQuery)).

After you have returned an item collection from a list by using a GetItem* method, you can specify a field name as an indexer and iterate through the collection to return values from the field. The following example displays the Due Date, Status, and Title values for each item in a collection.

Dim oItem As SPListItem

For Each oItem In  collItem

    Response.Write(SPEncode.HtmlEncode(oItem("Due Date").ToString()) + "<BR>")
    Response.Write(SPEncode.HtmlEncode(oItem("Status").ToString()) + "<BR>")
    Response.Write(SPEncode.HtmlEncode(oItem("Title").ToString()) + "<BR>")

Next oItem
foreach(SPListItem oItem in collItem)
{
    Response.Write(SPEncode.HtmlEncode(oItem["Due Date"].ToString()) + "<BR>");
    Response.Write(SPEncode.HtmlEncode(oItem["Status"].ToString()) + "<BR>");
    Response.Write(SPEncode.HtmlEncode(oItem["Title"].ToString()) + "<BR>");
}

Note

In addition to requiring a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace, the previous example requires a directive for the Microsoft.SharePoint.Utilities namespace.

The next example shows how to return all Title and Status values for the Tasks list on a SharePoint Web site.

Dim oWebsite As SPWeb = SPContext.Current.Web
Dim oList As SPList = oWebsite.Lists("Tasks")
Dim collItem As SPListItemCollection = oList.GetItems("Title", "Status")

Dim oItem As SPListItem
For Each oItem In  collItem

    Response.Write(SPEncode.HtmlEncode(oItem("Title").ToString()) + " :: " _
        & SPEncode.HtmlEncode(oItem("Status").ToString()) + "<BR>")

Next oItem
SPWeb oWebsite = SPContext.Current.Web;

SPList oList = oWebsite.Lists["Tasks"];
SPListItemCollection collItem = oList.GetItems("Title", "Status");

foreach(SPListItem oItem in collItem)
{
    Response.Write(SPEncode.HtmlEncode(oItem["Title"].ToString()) + " :: " + 
        SPEncode.HtmlEncode(oItem["Status"].ToString()) + "<BR>");
}

If request throttling has been implemented, inefficient queries may be blocked because of excessive lookup count or item count issues. You can improve the efficiency of a query and reduce lookup count issues by defining an SPQuery object that specifies a restricted set of view fields (ViewFields), and then passing this query object to the GetItems method, such as shown in the following example.

Dim oQuery As New SPQuery()
oQuery.Query = "<ViewFields><FieldRef Name = ""Title"" />" & 
    "<FieldRef Name = ""Status""/></ViewFields>"
Dim collItem As SPListItemCollection = oList.GetItems(oQuery)
SPQuery oQuery = new SPQuery();
oQuery.Query  =  "<ViewFields><FieldRef Name = \"Title\" />" +
    "<FieldRef Name = \"Status\"/></ViewFields>";
SPListItemCollection collItem = oList.GetItems(oQuery);

To address item count throttling issues, you may need to page results on item index by using the SPListItemCollectionPosition class.

Note

In addition to requiring a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace, the previous example requires a directive for the Microsoft.SharePoint.Utilities namespace.

You can also use indexers to modify values in a list. In the following example, a new list item is added to a collection and the values for a URL column are assigned to the item.

Dim oNewItem As SPListItem = oList.Items.Add()

oNewItem("URL_Field_Name") = "URL, _ Field_Description"

oNewItem.Update() 
SPListItem oNewItem = oList.Items.Add();

oNewItem["URL_Field_Name"] = "URL, Field_Description";

oNewItem.Update();

Note

The URL field type is unique because it involves two values (separated by a comma and a space), and in the above example these values are both assigned to the new item through a single indexer.

The following example uses the GetItemById(Int32) method to return an item, and then sets its Status and Title column values.

Dim oItem As SPListItem = oList.GetItemById(1) 

oItem("Status") = "Task_Status"
oItem("Title") = "Task_Title"

oItem.Update() 
SPListItem oItem = oList.GetItemById(1);

oItem["Status"]="Task_Status";
oItem["Title"]="Task_Title";

oItem.Update();

If you can specify the list of fields to retrieve for the item, and if none of the fields are Lookup types or field types that inherit from SPFieldLookup, you can improve performance by calling the GetItemByIdSelectedFields(Int32, []) method, instead of calling GetItemById(Int32).

Note

An indexer throws an ArgumentOutOfRange exception if it does not find the specified item.

For information about specific data formats that are used for list items in SharePoint Foundation, see the SPListItem class.

See Also

Reference

Microsoft.SharePoint

Microsoft.SharePoint.Administration

Concepts

How to: Return Items from a List

How to: Create or Delete SharePoint Lists

How to: Add or Delete List Items

How to: Read the Value of a Field in a List Item

Namespaces in the SharePoint Foundation Object Model

Using Visual Studio for SharePoint Development

Getting References to Sites, Web Applications, and Other Key Objects

Registering and Importing Namespaces