Compartilhar via


How to: Retrieve List Items

Applies to: SharePoint Foundation 2010

Available in SharePoint Online

To return items from a list, use the GetItemById() method to return a single item, or the GetItems(CamlQuery) method to return multiple items. You then use the Load<T>(T, []) method to attain list item objects that represent the items.

Retrieving items from a list

The GetItems(CamlQuery) method allows you to define a Collaborative Application Markup Language (CAML) query that specifies which items to return. You can pass an undefined CamlQuery object to return all items from the list, or use the ViewXml property to define a CAML query and return items that meet specific criteria.

The following example displays the ID, as well as the Title and Body column values, of the first 100 items in the Announcements list, starting with list items whose collection ID is greater than 10.

using System;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveListItems
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" +
                "<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>";
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(collListItem);

            clientContext.ExecuteQuery();

            foreach (ListItem oListItem in collListItem)
            {
                Console.WriteLine("ID: {0} \nTitle: {1} \nBody: {2}", oListItem.Id, oListItem["Title"], oListItem["Body"]);
            }
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveListItems

        Shared Sub Main ()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"

            Dim clientContext As New ClientContext(siteUrl)
            Dim oList As SP.List = clientContext.Web.Lists.GetByTitle("Announcements")

            Dim camlQuery As New CamlQuery()
            camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" + _
                "<Value Type='Number'>10</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>"

            Dim collListItem As ListItemCollection = oList.GetItems(camlQuery)

            clientContext.Load(collListItem)

            clientContext.ExecuteQuery()

            Dim oListItem As ListItem
            For Each oListItem In collListItem
                Console.WriteLine("ID: {0} " + ControlChars.Lf + "Title: {1} " + _
                                  ControlChars.Lf + "Body: {2}", oListItem.Id, _
                                  oListItem("Title"), oListItem("Body"))
            Next oListItem

        End Sub
    End Class
End Namespace

The previous example loads the collection of items specified by the CAML query, and all default properties can subsequently be accessed on each list item object that is returned. Use the Include<TSource>(IQueryable<TSource>, []) method to improve performance by limiting the amount of data that is returned through the query by specifying which properties are available.

Using the Include method

Four properties of ListItem are not available by default when you return list items-- DisplayName, EffectiveBasePermissions, HasUniqueRoleAssignments, and RoleAssignments. The previous example returns a PropertyOrFieldNotInitializedException if you attempt to access one of these properties. To access these properties, use the Include<TSource>(IQueryable<TSource>, []) method within a LINQ query expression to explicitly return them. For more information about non-default properties, see Data Retrieval Overview.

To modify the previous example so that it returns the value of DisplayName and HasUniqueRoleAssignments, you can replace the previous call to the Load<T>(T, []) method with a call that uses a LINQ query, which in C# requires a reference to the System.Linq namespace.

Note

When you use LINQ to create queries against the client object model, you are using LINQ to Objects, not the LINQ to SharePoint provider, which can only be used when you write code against the server object model.

using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveListItemsInclude
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");

            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "<View><RowLimit>100</RowLimit></View>";

            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(collListItem,
                 items => items.Include(
                    item => item.Id,
                    item => item.DisplayName,
                    item => item.HasUniqueRoleAssignments));

            clientContext.ExecuteQuery();

            foreach (ListItem oListItem in collListItem)
            {
                Console.WriteLine("ID: {0} \nDisplay name: {1} \nUnique role assignments: {2}",
                    oListItem.Id, oListItem.DisplayName, oListItem.HasUniqueRoleAssignments);
            }
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveListItemsInclude

        Shared Sub Main ()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"

            Dim clientContext As New ClientContext(siteUrl)
            Dim oList As List = clientContext.Web.Lists.GetByTitle("Announcements")

            Dim camlQuery As New CamlQuery()
            camlQuery.ViewXml = "<View><RowLimit>100</RowLimit></View>"

            Dim collListItem As ListItemCollection = oList.GetItems(camlQuery)

            clientContext.Load(collListItem, _
                Function(items) items.Include( _
                    Function(item) item.Id, _
                    Function(item) item.DisplayName, _
                    Function(item) item.HasUniqueRoleAssignments))


            clientContext.ExecuteQuery()

            Dim oListItem As ListItem
            For Each oListItem In collListItem
                Console.WriteLine("ID: {0} " + ControlChars.Lf + _
                                  "Display name: {1} " + ControlChars.Lf + _
                                  "Unique role assignments: {2}", oListItem.Id, _
                                  oListItem.DisplayName, oListItem.HasUniqueRoleAssignments)
            Next oListItem

        End Sub
    End Class
End Namespace

Because this example uses the Include<TSource>(IQueryable<TSource>, []) method, only the specified properties are available after query execution. Therefore, you receive a PropertyOrFieldNotInitializedException if you attempt to access other properties beyond those that have been specified. In addition, you receive this error if you attempt to use properties such as ContentType or ParentList to access the properties of containing objects.

Retrieving specific fields from a specified number of items

The following example shows how to retrieve specific fields from only the first five items in a list. Because only the Title and Body columns are specified, these are the only properties that are available.

using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveSpecificItemsFields
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");

            CamlQuery camlQuery = new CamlQuery();
            ListItemCollection collListItem = oList.GetItems(camlQuery);

            clientContext.Load(
                collListItem,
                items => items.Take(5).Include(
                item => item["Title"],
                item => item["Body"]));

            clientContext.ExecuteQuery();

            foreach (ListItem oListItem in collListItem)
            {
                Console.WriteLine("Title: {0} \nBody: {1}\n", oListItem["Title"], oListItem["Body"]);
            }
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveSpecificItemsFields

        Shared Sub Main ()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"

            Dim clientContext As New ClientContext(siteUrl)
            Dim oList As SP.List = clientContext.Web.Lists.GetByTitle("Announcements")

            Dim camlQuery As New CamlQuery()
            Dim collListItem As ListItemCollection = oList.GetItems(camlQuery)

            clientContext.Load(collListItem, _
                Function(items) items.Take(5).Include( _
                    Function(item) item("Title"), _
                    Function(item) item("Body")))

            clientContext.ExecuteQuery()

            Dim oListItem As ListItem
            For Each oListItem In collListItem
                Console.WriteLine("Title: {0} " + ControlChars.Lf + "Body: {1}" + _
                                  ControlChars.Lf, oListItem("Title"), oListItem("Body"))
            Next oListItem

        End Sub
    End Class
End Namespace

The previous example passes the CamlQuery object to the Load<T>(T, []) method without specifying a CAML query string, which would normally return all list items, but in this case the Take<TSource>(IQueryable<TSource>, Int32) method limits the number of items that are returned.

Retrieving items from all the lists in a Web site

The following example shows how to retrieve the titles of the first 10 items in all the lists of a Web site.

using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveFirstTenItemsAllLists
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            ListCollection collList = clientContext.Web.Lists;

            clientContext.Load(
                collList,
                lists => lists.Where(
                    list => list.Hidden == false).Include(
                    list => list.Title,
                    list => list.Items.Take(10)));

            clientContext.ExecuteQuery();

            foreach (SP.List oList in clientContext.Web.Lists)
            {
                string listTitle = oList.Title;
                int itemCount = oList.Items.Count;

                Console.WriteLine("List {0} returned with {1} items", listTitle, itemCount);
            }
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveFirstTenItemsAllLists

        Shared Sub Main ()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"

            Dim clientContext As New ClientContext(siteUrl)
            Dim collList As ListCollection = clientContext.Web.Lists

            clientContext.Load(collList, _
                Function(lists) lists.Where( _
                    Function(list) list.Hidden = False).Include( _
                        Function(list) list.Title, _
                        Function(list) list.Items.Take(10)))

            clientContext.ExecuteQuery()

            Dim oList As SP.List
            For Each oList In clientContext.Web.Lists
                Dim listTitle As String = oList.Title
                Dim itemCount As Integer = oList.Items.Count

                Console.WriteLine("List {0} returned with {1} items", listTitle, itemCount)
            Next oList

        End Sub
    End Class
End Namespace

Note

In SharePoint Foundation 2010 the load(clientObject) method of JavaScript does not support using the Where<TSource>(IQueryable<TSource>, Expression<Func<TSource, Boolean>>) method that is used in the previous example.

Retrieving items using list item collection position

You can use the ListItemCollectionPosition class to implement paging list item retrieval according to the position of items relative to their collection. Use the RowLimit element to specify the number of items to return per page. The following example loops through all the items in an Announcements list, using the ListItemCollectionPosition property of the CamlQuery class, and the ListItemCollectionPosition property of the ListItemCollection class, to alternately get or set the position of each iteration through a collection, according to five items per page. As long as it is true that five items have been returned for a page, the loop continues and uses the PagingInfo property to display paging information, along with information about each of the five items that are returned. When less than five items are returned for a page, the loop concludes.

using System;
using System.Linq;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class UsingItemCollectionPosition
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            SP.List oList = clientContext.Web.Lists.GetByTitle("Announcements");

            ListItemCollectionPosition itemPosition = null;

            while (true)
            {
                CamlQuery camlQuery = new CamlQuery();

                camlQuery.ListItemCollectionPosition = itemPosition;

                camlQuery.ViewXml = "<View><ViewFields><FieldRef Name='ID'/>" + 
                    "<FieldRef Name='Title'/><FieldRef Name='Body'/>" + 
                    "</ViewFields><RowLimit>5</RowLimit></View>";

                ListItemCollection collListItem = oList.GetItems(camlQuery);

                clientContext.Load(collListItem);

                clientContext.ExecuteQuery();

                itemPosition = collListItem.ListItemCollectionPosition;

                foreach (ListItem oListItem in collListItem)
                {
                    Console.WriteLine("Title: {0}: \nBody: {1}", oListItem["Title"], oListItem["Body"]);
                }

                if (itemPosition == null)
                {
                    break;
                }

                Console.WriteLine("\n" + itemPosition.PagingInfo + "\n");
            }
        }

    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class UsingItemCollectionPosition

        Shared Sub Main ()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"

            Dim clientContext As New ClientContext(siteUrl)
            Dim oList As SP.List = clientContext.Web.Lists.GetByTitle("Announcements")

            Dim itemPosition As ListItemCollectionPosition = Nothing

            While True

                Dim camlQuery As New CamlQuery()
                camlQuery.ListItemCollectionPosition = itemPosition

                camlQuery.ViewXml = "<View><ViewFields><FieldRef Name='ID'/>" + _
                    "<FieldRef Name='Title'/><FieldRef Name='Body'/>" + _
                    "</ViewFields><RowLimit>5</RowLimit></View>"

                Dim collListItem As ListItemCollection = oList.GetItems(camlQuery)

                clientContext.Load(collListItem)

                clientContext.ExecuteQuery()

                itemPosition = collListItem.ListItemCollectionPosition

                Dim oListItem As ListItem
                For Each oListItem In collListItem
                    Console.WriteLine("Title: {0}: " + ControlChars.Lf + _
                        "Body: {1}", oListItem("Title"), oListItem("Body"))
                Next oListItem

                If itemPosition Is Nothing Then
                    Exit While
                End If

                Console.WriteLine((ControlChars.Lf + itemPosition.PagingInfo + ControlChars.Lf))
            End While

        End Sub
    End Class
End Namespace

For information and examples about retrieving client objects within the context of the SharePoint Foundation Silverlight object model, see Using the Silverlight Object Model.

See Also

Concepts

Data Retrieval Overview

SharePoint 2010 Client Object Model Guidelines

How to: Create, Update, and Delete List Items

Common Programming Tasks in the Managed Client Object Model

Other Resources

Code Snippet: Get Item Data from an External List on the Client

Client Class Library

JavaScript Class Library