How to: Grouping groups


Today I would like to show a tip for grouping active directory groups using LINQ to objects.

Suppose this scenario: You wanna retrieve all the roles a user belongs, grouping them by their domain name, as shows:

Groups under:
– Group name: All
– Group name: LOCAL
Groups under: BUILTIN
– Group name: Users
– Group name: Administrators
– Group name: xxx1
– Group name: xxx2
– Group name: xxx3
– Group name: xxx4
– Group name: xxxN
Groups under: NT AUTHORITY
– Group name: INTERACTIVE
– Group name: Authentified users

(*) As you can imagine, some names have been deleted for security reasons :-)

We can accomplish this using only one LINQ to objects sentence, and a couple of extension methods (extending the NTAccount class):

public static IOrderedEnumerable<IGrouping <string, NTAccount>>
    GetGroupsUnderDomains(this WindowsIdentity identity)
    var groups =
        from grIdentity in identity.Groups
        where grIdentity.IsValidTargetType(typeof(NTAccount))
        select grIdentity.Translate(typeof(NTAccount)) as NTAccount into ntAccounts
        let domainName = ntAccounts.GetDomainName()
        orderby domainName
        group ntAccounts by domainName
            into domainGroups
            orderby domainGroups.Key
            select domainGroups;
    return groups;

public static string GetDomainName(this NTAccount account)
    string[] split = account.Value.Split('\\');
    return split.Length == 1 ? string.Empty : split[0];

public static string GetAccountName(this NTAccount account)
    string[] split = account.Value.Split('\\');
    return split[split.Length - 1];

Awesome! LINQ rules :-)

If you would try this code, it’s quite simple:

var groups = WindowsIdentity.GetCurrent().GetGroupsUnderDomains();
foreach (var dg in groups)
    Console.WriteLine(string.Format("Groups under: {0}", dg.Key));
    foreach (var g in dg)
        Console.WriteLine(string.Format("  - Group name: {0}", g.GetAccountName()));

HYEI, happy coding!

December 2010

Published by

Lluis Franco

The one who loves programming. In love with C#, Java, F#, SQL, async patterns. Blogger, Speaker, Geek & family guy living in Andorra. Microsoft MVP 2002-2016

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s