我需要在ASP.NET网站上构建一个所有角色的列表,并将分配给给定用户的角色标记为标记,即Roles API允许我获取用户的所有角色和角色。我希望将这些结合起来,以便能够为用户显示角色网格,显示所有角色,并在分配给用户的角色上显示复选标记。如何改进以下LINQ to Objects工作?
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;
}
答案 0 :(得分:3)
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 };
尝试一下它的工作代码希望这可以帮助你。
由于
Shakeeb Ahmed
答案 1 :(得分:2)
这应该可以解决问题。
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)
});
}
注意:使用IEnumerable<T>.Any扩展方法会在找到匹配项后立即返回true,因此在找到匹配项后,它不会不必要地迭代其余的集合。