ProfK
ProfK

Reputation: 51063

User Role Query with LINQ

I need to build a list of all roles on an ASP.NET web site, with those assigned to a given user flagged, i.e. the Roles API allows me to get all roles, and roles for a user. I want to combine these to be able to show a roles grid for a user, showing all roles, with a check mark on those assigned to the user. How can I improve the following LINQ to Objects effort?

public IEnumerable<UserRoleIndicator> GetRoleIndicators(string userName)
{
    // GetRolesForUser and GetAllRoles bith return string[].
    var rolesForUser = _roleProvider.GetRolesForUser(userName)
        .Select(r => new UserRoleIndicator { RoleName = r, InRole = true });
    var rolesNotForUser = _roleProvider.GetAllRoles()
        .Where(r => !rolesForUser.Contains(new UserRoleIndicator { RoleName = r, InRole = true }))
        .Select(r => new UserRoleIndicator { RoleName = r, InRole = false });
    var rolesList = rolesForUser.Union(rolesNotForUser);
    return rolesList;
}

Upvotes: 2

Views: 2831

Answers (2)

Shakeeb Ahmed
Shakeeb Ahmed

Reputation: 1808

        string[] roles = new string[] { "Admin", "Super", "Normal" };
        string[] userroles = new string[] { "Admin", "Normal" };

        var query = from r in roles
                    join u in userroles on r equals u
                    into temproles
                    from urs in temproles.DefaultIfEmpty()
                    select new UserRoleIndicator { RoleName = r, InRole = r == urs ? true : false };

Try this one its a working code hope this helps you.

Thanks

Shakeeb Ahmed

Upvotes: 3

Doctor Jones
Doctor Jones

Reputation: 21664

This should do the trick.

public IEnumerable<UserRoleIndicator> GetRoleIndicators(string userName)
{
    var roles = _roleProvider.GetAllRoles();
    var userRoles = _roleProvider.GetRolesForUser(userName);

    return roles.Select(role => new UserRoleIndicator 
    { 
        RoleName = role,
        InRole = userRoles.Any(userRole => role == userRole) 
    }); 
}

Note: using the IEnumerable<T>.Any extension method returns true as soon as a match is found, so it won't needlessly iterate though the rest of the collection after it has already found a match.

Upvotes: 2

Related Questions