Partilhar via


How to: Retrieve Lists

Applies to: SharePoint Foundation 2010

Available in SharePoint Online

Working with list objects is similar to working with Web site objects. Start by using the ClientContext() constructor and passing a URL or URI to return a specific request context. You can then use the Lists property of the Web class to get the collection of lists in the Web site.

Retrieving all properties of all lists in a Web site

To return all the lists of a Web site, load the list collection through the Load<T>(T, []) method and then call ExecuteQuery() or ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler). The following example displays the URL of the Web site and the date and time that the list was created.

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

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

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

            clientContext.Load(collList);

            clientContext.ExecuteQuery();

            foreach (SP.List oList in collList)
            {
                Console.WriteLine("Title: {0} Created: {1}", oList.Title, oList.Created.ToString());
            }
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveAllListProperties

        Shared Sub Main()

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

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

            clientContext.Load(collList)

            clientContext.ExecuteQuery()

            Dim oList As SP.List
            For Each oList In collList
                Console.WriteLine("Title: {0} Created: {1}", oList.Title, oList.Created.ToString())
            Next oList
        End Sub        
    End Class
End Namespace

Retrieving only specified properties of lists

The previous example returns all properties of the lists in a Web site, but to reduce unnecessary data transference between client and server, you can use LINQ query expressions to specify which properties to return. The following example uses the Include<TSource>(IQueryable<TSource>, []) method within a LINQ expression to return only the title and ID of each list in the collection.

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

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

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

            clientContext.Load(
                collList,
                lists => lists.Include(
                    list => list.Title, 
                    list => list.Id));

            clientContext.ExecuteQuery();

            foreach (SP.List oList in collList)
            {
                Console.WriteLine("Title: {0} ID: {1}", oList.Title, oList.Id.ToString("D"));
            }
        }
   }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveSpecificListProperties

        Shared Sub Main()

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

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

            clientContext.Load(collList, Function(lists) lists. _
                                             Include(Function(list) list.Title, _
                                                     Function(list) list.Id))
            clientContext.ExecuteQuery()

            Dim oList As SP.List
            For Each oList In collList
                Console.WriteLine("Title: {0} ID: {1}", oList.Title, oList.Id.ToString("D"))
            Next oList
        End Sub        
    End Class
End Namespace

In the previous example, only the title and ID of each list object becomes available after ExecuteQuery() is called. If you try to display, for example, oList.ParentWebUrl, you receive a PropertyOrFieldNotInitializedException.

Storing retrieved lists in a collection

As seen in the following example, you can use the LoadQuery() method, instead of the Load<T>(T, []) method, to store the return value in another collection instead of storing it in the Lists property.

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

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

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

            IEnumerable<SP.List> resultCollection = clientContext.LoadQuery(
                collList.Include(
                    list=>list.Title,
                    list=>list.Id));

            clientContext.ExecuteQuery();

            foreach (SP.List oList in resultCollection)
            {
                Console.WriteLine("Title: {0} ID: {1}", oList.Title, oList.Id.ToString("D"));
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveSpecificListPropertiesToCollection

        Shared Sub Main()

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

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

            Dim queryResult As IEnumerable(Of SP.List) = clientContext.LoadQuery( _
                collList.Include(Function(list) list.Title, _
                                 Function(list) list.Id))

            clientContext.ExecuteQuery()

            Dim oList As SP.List
            For Each oList In queryResult
                Console.WriteLine("Title: {0} ID: {1}", oList.Title, oList.Id.ToString("D"))
            Next oList
        End Sub        
    End Class
End Namespace

Applying filters to list retrieval

You can use LINQ lambda expression syntax or LINQ query expression syntax to create filters for limiting the lists that are retrieved in a query, which requires that you set a reference to the System.Linq namespace.

The following example modifies the previous example by using a lambda expression as parameter for the LoadQuery() method to return only lists that contain items and that are not hidden.

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.

    IEnumerable<SP.List> resultCollection = clientContext.LoadQuery(
             collList.Include(
                 list => list.Title,
                 list => list.Id).Where(
                     list => list.ItemCount != 0
                         && list.Hidden != true));
    Dim resultCollection As IEnumerable(Of SP.List) = _
             clientContext.LoadQuery(collList.Include( _
                                     Function(list) list.Title, _
                                     Function(list) list.Id).Where( _
                                     Function(list) list.ItemCount <> 0 _
                                         AndAlso list.Hidden <> True))

To use standard LINQ query syntax, the parameter for the LoadQuery() method would instead be as follows.

    var queryExpression = from list
                          in collList.Include(
                              list => list.Title,
                              list => list.Id)
                          where list.ItemCount != 0
                              && list.Hidden != true
                          select list;

    IEnumerable<SP.List> resultCollection = clientContext.LoadQuery(queryExpression);
    Dim queryExpression = From list In collList.Include( _
                              Function(list) list.Title, Function(list) list.Id) _
                          Where list.ItemCount <> 0 _
                              AndAlso list.Hidden <> True _
                          Select list

    Dim resultCollection As IEnumerable(Of SP.List) = clientContext.LoadQuery(queryExpression)

The following example illustrates how to use LINQ syntax to retrieve only the first two lists from a Web site.

    IEnumerable<SP.List> resultCollection = clientContext.LoadQuery(
             collList.Take(2).Include(
                 list => list.Title,
                 list => list.Id));
    Dim resultCollection As IEnumerable(Of SP.List) = clientContext.LoadQuery(collList.Take(2) _
             .Include(Function(list) list.Title, _
             Function(list) list.Id))

Retrieving list fields from a Web site

As the following example shows, you can nest Include<TSource>(IQueryable<TSource>, []) methods to return metadata for both a list and its fields. The example returns all fields from all lists within a Web site and displays the title and internal name of all fields whose internal name contains the string "name".

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

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

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

            IEnumerable<SP.List> listInfo = clientContext.LoadQuery(
                collList.Include(
                    list => list.Title,
                    list => list.Fields.Include(
                        field => field.Title,
                        field => field.InternalName)));
 
             clientContext.ExecuteQuery();

            foreach (SP.List oList in listInfo)
            {
                FieldCollection collField = oList.Fields;

                foreach (SP.Field oField in collField)
                {
                    Regex regEx = new Regex("name", RegexOptions.IgnoreCase);
                    
                    if (regEx.IsMatch(oField.InternalName))
                    {
                        Console.WriteLine("List: {0} \n\t Field Title: {1} \n\t Field Internal Name: {2}", 
                            oList.Title, oField.Title, oField.InternalName);
                    }
                }
            }
        }
    }
}
Imports System
Imports System.Text.RegularExpressions
Imports Microsoft.SharePoint.Client
Imports SP = Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveSpecificListPropertiesToCollection

        Shared Sub Main()

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

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

            Dim listInfo As IEnumerable(Of SP.List) = clientContext.LoadQuery( _
                collList.Include( _
                    Function(list) list.Title, _
                    Function(list) list.Fields.Include( _
                        Function(field) field.Title, _
                        Function(field) field.InternalName)))

            clientContext.ExecuteQuery()

            Dim oList As SP.List
            For Each oList In listInfo
                Dim collField As FieldCollection = oList.Fields

                Dim oField As SP.Field
                For Each oField In collField

                    Dim regEx As New Regex("name", RegexOptions.IgnoreCase)

                    If regEx.IsMatch(oField.InternalName) Then
                        Console.WriteLine("List: {0} " + _
                            ControlChars.Lf + ControlChars.Tab + " Field Title: {1} " + _
                            ControlChars.Lf + ControlChars.Tab + " Field Internal Name: {2}", _
                            oList.Title, oField.Title, oField.InternalName)
                    End If
                Next oField
            Next oList
        End Sub 
    End Module
End Namespace

For information and an example about how to retrieve list data within the context of the SharePoint Foundation 2010 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 Lists

Common Programming Tasks in the Managed Client Object Model

Other Resources

Client Class Library