我有下面的代码片段。我想要一种GetPermissions方法,这样我将只获取那些具有item.Actions.XXXX.value = true
的枚举。我以前使用的是字典,所以我评论过的代码可以正常工作
public class ResourcePermissionModel
{
public ResourcePermissionModel();
public int ResourceId { get; set; }
public IEnumerable<Permission> Permissions { get; set; }
}
public enum Permission
{
View = 0,
Modify = 1,
Delete = 2,
Assign = 3
}
var resourcePerm= result.RoleAccess.Permissions
.Select(item => new ResourcePermissionModel()
{
ResourceId = Convert.ToInt32(item.Id),
Permissions = GetPermissions(item.Actions)
//Permissions = new Dictionary<LockboxService.Models.Enum.Permission, bool>
//{
// { LockboxService.Models.Enum.Permission.Assign, item.Actions.Assign.Value },
// { LockboxService.Models.Enum.Permission.Delete, item.Actions.Delete.Value },
// { LockboxService.Models.Enum.Permission.Modify, item.Actions.Modify.Value },
// { LockboxService.Models.Enum.Permission.View, item.Actions.Use.Value }
//}
}).ToList();
private IEnumerable<Permission> GetPermissions(ResourceActionsBase actions)
{
//what to enter here?
}
答案 0 :(得分:1)
您可以使用收益回报率:
private IEnumerable<Permission> GetPermissions(ResourceActionsBase actions)
{
if (actions.Use.Value)
yield return Permission.View;
if (actions.Modify.Value)
yield return Permission.Modify;
if (actions.Delete.Value)
yield return Permission.Delete;
if (actions.Assign.Value)
yield return Permission.Assign;
}
您可能想在对ToList()
的调用之后添加GetPermissions
,否则每次从Permissions
获得ResourcePermissionModel
时,它都会推迟执行。
还请注意,如果您添加更多权限,我认为这种方法的伸缩性很差。在这种情况下,如果您可以实际更改模型或使用从模型属性到Permission-Values的静态映射