目前我有:
public enum ApplicationRoles
{
Undefined = 0,
Basic = 1,
Admin = 2
}
// within a method:
bool? isAuthorized = null;
string[] allowedRoles = { "Admin" };
List<ApplicationRoles> userRoles = new List<ApplicationRoles>();
userRoles.Add(ApplicationRoles.Admin);
foreach (string role in allowedRoles)
{
foreach (ApplicationRoles appRole in userRoles)
{
if (appRole != ApplicationRoles.Undefined)
isAuthorized = role.ToLower() == appRole.ToString().ToLower();
}
if ((bool)isAuthorized)
break;
}
在这个例子中,isAuthorized将返回true。
如何将其转换为Linq语句?
答案 0 :(得分:2)
您正在寻找Any
方法:
allowedRoles
.Any(role => user.Roles.Any(r => r != ApplicationRoles.Undefined &&
role.ToLower() == r.ToString().ToLower()));
如果您只想检查一个角色,则不需要allowedRoles
数组:
user.Roles.Any(r => r.ToLower() == "admin");
答案 1 :(得分:1)
您不应将任何值存储为硬编码字符串;毕竟,这就是枚举的用途。
var allowedRoles = new HashSet<ApplicationRoles> { ApplicationRoles.Admin };
bool isAuthorized = userRoles.Any(r => allowedRoles.Contains(r));
这种方法也适用于数组。
var allowedRoles = new[] { ApplicationRoles.Admin };
var userRoles = new[] { ApplicationRoles.Basic };
bool isAuthorized = userRoles.Any(r => allowedRoles.Contains(r));
答案 2 :(得分:0)
怎么样?
var allowedRoles = Enum.GetValues(typeof(ApplicationRoles))
.Cast<ApplicationRoles>()
.Except(ApplicationRoles.Undefinied); // allow all except undefined
bool isAuthorized = userRoles.Any(r => allowedRoles.Contains(r));
这样你就不需要乱用任何字符串比较了。