Share via


Count or GroupBy list item based on Person or Group column

Hello All,

Last week someone asked one question in the forum about counting the item based on person or group column. However, there are many ways to do this but one simple way is with a mix of CAML and LINQ.  You can also apply the same code to any list column instead of person or group. This code is tested in SP 2010 but should work in other versions as well.
 
My Test List Structure:

Title

User Name

Test1

Hemendra

Test2

John

Test3

Maria

Test4

Hemendra

Test5

John

Test6

Hemendra

Test7

Maria

Test8

John

Test9

Hemendra

Result should be:

User Name

Count

Hemendra

4

John

3

Maria

2

Add two additional namespaces in your visual web part:
using System.Data;
using System.Linq;

Add "System.Data.DataSetExtensions" as a reference in your solution. Then copy paste below code on button click event. Make sure to change the list name and column name in below code. (In this case , List Name : Text, Column Name: MultiUsers)

using (SPSite Site = new SPSite("siteURL"))
           {
               using (SPWeb Web = Site.OpenWeb())
               {
                   SPList list = Web.Lists.TryGetList("Test");
                   SPQuery query = new  SPQuery(); // query for all the items
                   DataTable dt = list.GetItems(query).GetDataTable(); 
                   if (dt != null && dt.Rows.Count > 0)
                   {
                       var groupedList = from row in  dt.AsEnumerable()
                       group row by row.Field<string>("MultiUsers") into groupedTable
                       orderby groupedTable.Key 
                        select new
                           {   Key = groupedTable.Key, 
                                UserCount = groupedTable.Count(), 
                                 groupedRows = groupedTable.CopyToDataTable() 
                            };
 
                       DataTable dt1 = new  DataTable();
                       dt1.Columns.Add("User Name", typeof(string));
                       dt1.Columns.Add("Count", typeof(int));
                       foreach (var items in groupedList)
                       {
                           string UserName = items.Key; //User Name
                           int count = items.UserCount; // count rows
                           DataRow dtRow = dt1.NewRow();
                           dtRow["User Name"] = UserName;
                           dtRow["Count"] = count;
                           dt1.Rows.Add(dtRow);
                       }
                       GridView1.DataSource = dt1;
                       GridView1.DataBind();
             }}}

Hope it could help to another.