1

I have a lot of list views.

Each view is displayed having group by name such as pending, working, complete ,......

I need to count each item inside group.

I need camel query in c# to count each group have once i pass parameter(siteurl,listname,viewname)

1

You can use the below code, Add Microsoft.SharePoint and Microsoft.SharePoint.Security Namespaces.

    public static int GetItemCount(string SiteUrl, string listName, string viewName)
        {
            int count = 0;
            try
            {
                SPListItemCollection items = null;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteUrl))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPList list = oWeb.Lists.TryGetList(listName);
                            if (list == null)
                                throw new Exception(string.Format("List with List Name: {0} not found at url {1}", listName, SiteUrl));
                            SPView view = list.Views[viewName];
                            SPQuery ViewQuery = new SPQuery(view);
                            ViewQuery.ViewFields = "<FieldRef Name='ID'/>";   
ViewQuery.RowLimit = 0;
                            if (view == null)
                                throw new Exception(string.Format("View with View Name: {0} not found in List {1}", viewName, listName));
                            items = list.GetItems(ViewQuery);
                            if (items != null)
                                count = items.Count;
                        }
                    }
                });

            }
            catch (Exception ex)
            {
                // Logs your Exception
            }

            return count;
        }
2
  • This can be optimized since all we need is count. Use the view's filter, but don't fetch all columns, just fetching ID is enough. – Prakash Jan 18 '16 at 17:31
  • @Prakash-CrowCanyon Thanks, I have updated the Optimized Code. – Akarsh Gupta Jan 18 '16 at 19:32
0

You can use the below code to get count of items for particular list view

using (SPSite oSiteCollection = new SPSite(strUrl))
{
    using(SPWeb oWebsite = oSiteCollection.AllWebs["Website_Name"])
    {
     SPList oList = oWebsite.Lists["List_Name"];
     string viewGUID = list.Views["View_Name"].ID.ToString("B").ToUpper();
    SPQuery query = new SPQuery() { Query = "<OrderBy><FieldRef Name='Title' /></OrderBy>" };
     SPListItemCollection items = list.GetItems(query,viewGUID);
     int count = items.Count;
    }
}
1
  • Why do we need OrderBy here? Will it alter count in any way? – Prakash Jan 18 '16 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.