Search code examples
c#azuremicrosoft-graph-api

In a single call Get all the Users in a group along with the number of groups that each user belongs to?


we are using the following query to get the list of all the members in a group

https://graph.microsoft.com/v1.0/groups/{id}/members

requirement

  1. We need to get all the users in a group and also the count of the groups each users belongs too in a single call, so that we dont delete users who are part of multiple groups.

couldn't find any information on searching on multiple entities (group and user).


Solution

  • With a single query, you can retrieve users members of a specific group and expand groups where the user is a member of.

    GET /v1.0/groups/{group_id}/members/microsoft.graph.user?$expand=memberof/microsoft.graph.group($select=id)
    

    Counting must be done on the client

    If you prefer the Microsoft Graph .NET SDK

    var result = await graphClient.Groups["{group-id}"].Members.GraphUser.GetAsync((rc) =>
    {
        rc.QueryParameters.Expand = new string []{ "memberof/microsoft.graph.group($select=id)" };
    });
    
    var pageIterator = PageIterator<User, UserCollectionResponse>.CreatePageIterator(graphClient, result, (user) =>
    {
        var groupCount = user.MemberOf.Count;
        return true;
    });
    
    await pageIterator.IterateAsync();