Monday 8 June 2015

Retrieve all SharePoint lists in a web using Client Side Object Model

This example retrieves all SharePoint lists in a SharePoint website. To compile this code you will need to add a using statement for System.Linq.


// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// Retrieve all lists from the server. 
context.Load(web.Lists, 
             lists => lists.Include(list => list.Title, // For each list, retrieve Title                                                            and Id. 
                                    list => list.Id)); 

// Execute query. 
context.ExecuteQuery(); 

// Enumerate the web.Lists. 
foreach (List list in web.Lists) 
{ 
    label1.Text = label1.Text + ", " + list.Title; 
} 






Alternatively, we can use the LoadQuery method to store the return value in another collection, rather than use the web.Lists property. we also need to add using statements for System.Collections.Generic and System.Linq. Also, add an alias to the using statement for Microsoft.SharePoint.Client namespace so we can refer to its classes unambiguously. For example, using SP = Microsoft.SharePoint.Client;.




// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// Retrieve all lists from the server, and put the return value in another 
// collection instead of the web.Lists. 
IEnumerable result = context.LoadQuery(web.Lists.Include( // For each list, retrieve Title and Id.
                                                                   list => list.Title, 
                                                                   list => list.Id)); 

// Execute query. 
context.ExecuteQuery(); 

// Enumerate the result. 
foreach (List list in web.Lists) 
{ 
    label1.Text = label1.Text + ", " + list.Title; 
} 

No comments: