Get sharepoint lists with more than 5000 items using csom

In this article, I am going to write C# code to retrieve sharepoint lists with more than 5000 items using Clinet Object Model (csom). The magic limit 5000 is a default list view threshold in sharepoint online. To find total lists items in a list, we don’t need to iterate all items from list, instead we can get it from the property ItemCount in sharepoint client object model’s List object.

Get all Lists with ItemCount

Use the below C# code to get all sharepoint lists with their total item count.

public static void GetAllListsWithItemCount()
{
    string sitrUrl = "https://Tenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        Web site = ctx.Web;
        ctx.Credentials = //Use your credentials
        ctx.Load(site, a => a.Lists.Include(l => l.Title, l => l.ItemCount));
        ctx.ExecuteQuery();

        foreach (var list in site.Lists)
        {
            Console.WriteLine(list.Title+" : "+ list.ItemCount);
        }
    }
}

Get Lists with more than 5000 items

The above code returns all the lists with itemcount. To get the lists with more than 5000 items, we need to filter lists with the ItemCount property in linq query.

public static void GetListsWithMoreThan5000Items()
{
    string sitrUrl = "https://Tenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        Web site = ctx.Web;
        ctx.Credentials = //Use your credentials
        ctx.Load(site, a => a.Lists.Where(l => l.ItemCount > 5000),
            a => a.Lists.Include(l => l.Title, l => l.ItemCount));
        ctx.ExecuteQuery();

        foreach (var list in site.Lists)
        {
            Console.WriteLine(list.Title + " : " + list.ItemCount);
        }
    }
}

Get Document Libraries with more than 5000 items

You can also get only document libraries by filtering List object with BaseType property.

public static void GetLibrariesWithMoreThan5000Items()
{
    string sitrUrl = "https://Tenant.sharepoint.com/sites/contosobeta";
    using (var ctx = new ClientContext(sitrUrl))
    {
        Web site = ctx.Web;
        ctx.Credentials = //Use your credentials
        ctx.Load(site, a => a.Lists.Where(l => l.BaseType == BaseType.DocumentLibrary &&
                 l.ItemCount > 10 && !l.Hidden),
        a=>a.Lists.Include(l => l.Title, l => l.ItemCount));
        ctx.ExecuteQuery();

        foreach (var library in site.Lists)
        {
            Console.WriteLine(library.Title + " : " + library.ItemCount);
        }
    }
}

Advertisement

Leave a Comment