Export (0) Print
Expand All

How to: Retrieve List Items

SharePoint 2010

Published: May 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.

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"]);
            }
        }
    }
}

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.

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 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);
            }
        }
    }
}

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.

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"]);
            }
        }
    }
}

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.

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);
            }
        }
    }
}
NoteNote

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.

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");
            }
        }

    }
}

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

Community Additions

ADD
Show:
© 2014 Microsoft