how to count Records programatically using c# List object

Mohammad Qasim 576 Reputation points
2020-08-24T12:51:09.7+00:00

Greetings,

i have data into list like below,i want to count progrmatically using c#

ID, User ID UserName, Documentname
1 5 A Test
2 5 A Testa
3 6 B Testb
4 7 C Testc1
5 7 C Testc
6 8 AB Testabd

Requirement
I want "count" document, based on user on desc order, so output would be like this

Name, Total Docs
A 2
B 1
C 2
AB 1

SharePoint Server Management
SharePoint Server Management
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Management: The act or process of organizing, handling, directing or controlling something.
2,955 questions
{count} votes

5 additional answers

Sort by: Most helpful
  1. sadomovalex 3,631 Reputation points
    2020-08-24T15:30:50.46+00:00

    hi, do you have SP on-prem or SP online? For on-prem you may use basic server object model for your need:

        var web = ...;
        var list = web.Lists["MyList"];
        var dict = new Dictionary<int, int>();
        foreach (SPListItem item in list.Items)
        {
            int userId = (int)item["User ID"];
            if (!dict.ContainsKey(userId))
            {
                dict.Add(userId, 0);
            }
            dict[userId]++;
        }
    

    After that dictionary will have necessary date: user ids and count of list items. You may put it to report or to other Sharepoint list. If you will need to add user name you may get it from web.SiteUsers.GetByID(userId) call.

    0 comments No comments

  2. Mohammad Qasim 576 Reputation points
    2020-08-24T16:49:38.457+00:00

    yes I have sp2016 on prem ,how to count and distint or group by ?
    do u have any example to be shared ??

    0 comments No comments

  3. MichaelHan-MSFT 18,036 Reputation points
    2020-08-25T08:39:12.497+00:00

    You could use LINQ to SharePoint List items to achieve this. Below is my demo code for you: demo.txt

    Below is my test result:

    Test List

    20158-image.png

    Output

    20195-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

  4. Mohammad Qasim 576 Reputation points
    2020-08-25T11:16:59.527+00:00

    I have spquery object , where I have written query to pass into list.getitmes(ospquery).

    using spquery , how to do above method ( as u shared example above ) ?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.