Sharepoint - How to get List by Url using SharePoint 2013 CSOM

For those who are still looking for the answer. SharePoint 2013 (since SP1 at least see UPD below) contains special method Web.GetList. It accepts site-relative url for the list, i.e. site/dev/lists/mylist.

Sample code for .NET object model:

var ctx = new ClientContext("http://sp2013dev/sites/dev");
var list = ctx.Web.GetList("sites/dev/lists/Addresses");
ctx.Load(list);
ctx.ExecuteQuery();    
Console.WriteLine(list.Title);

The same situation for JavaScript object model (except the fact that msdn documentation is lacking and you don't find this method here at the moment of writing this, May 2015):

var context = SP.ClientContext.get_current();
var list = context.get_web().getList("/sites/dev/Lists/Addresses"); 
context.load(list);
context.executeQueryAsync(function() { 
    alert("loaded!"); 
    }, function() { 
    alert("failed!"); 
});

Now we don't need all this hacks with folder or list properties.

UPD:

Just tested that this method is not included in SP1. It works starting from February 2015 CU (sorry, can't check the exact CU number)


This seems to be pretty close in performance:

context.Load(lists, all => all
  .Where(l => l.RootFolder.Name == "MyListUrl")
  .Include(l => l.Id));
context.ExecuteQuery();
list = lists.Single();

If you need to get this by server-relative url you would need to parse the web url and list url first.


Yet another version to load List by server relative Url using CSOM.

The solution consists of the following steps:

  1. Retrieve list Folder object using Web.GetFolderByServerRelativeUrl method
  2. Retrieve List by specifying List ID stored in vti_listname property from Folder.Properties object

Code:

static class WebExtensions
{
    /// <summary>
    /// Load List by server relative Url
    /// </summary>
    /// <param name="web"></param>
    /// <param name="listUrl"></param>
    /// <returns></returns>
    public static List LoadListByUrl(this Web web, string listUrl)
    {
        var ctx = web.Context;
        var listFolder = web.GetFolderByServerRelativeUrl(listUrl);
        ctx.Load(listFolder.Properties);
        ctx.ExecuteQuery();
        var listId = new Guid(listFolder.Properties["vti_listname"].ToString());
        var list = web.Lists.GetById(listId);
        ctx.Load(list);
        ctx.ExecuteQuery();
        return list;
    }
}

Usage

using(var ctx = new ClientContext(webUrl))
{
    ctx.Credentials = new SharePointOnlineCredentials(userName,securePassword);
    var tasksList = ctx.Web.LoadListByUrl("Lists/Tasks");
    Console.WriteLine(tasksList.Title);
}

Cons:

  1. Only SharePoint 2013 CSOM is supported
  2. Requires two separate requests to server