简体   繁体   English

如何用标志枚举属性展平对象集合?

[英]How to Flatten a Collection of Objects with Flag Enum Properties?

I have a Role object that will have several flag enum properties, one for each related object. 我有一个Role对象,它将具有几个flag枚举属性,每个相关对象一个。 A user can belong to multiple roles. 一个用户可以属于多个角色。 I want to get the collection of roles and flatten it to a single representation and use that to limit UI features. 我想获取角色集合并将其展平为单个表示形式,并使用它来限制UI功能。 How do I flatten the collection? 如何展平藏品?

Here's some example code from my LINQPad test: 这是我的LINQPad测试中的一些示例代码:

ICollection<Role> roles = new List<Role>();

roles.Add(new Role {
    Name = "Administrator",
    Object1Defaults = DefaultPermissions.Add | DefaultPermissions.Edit | DefaultPermissions.Remove,
    Object2Defaults = DefaultPermissions.Add | DefaultPermissions.Edit | DefaultPermissions.Remove
});
roles.Add(new Role {
    Name = "Manager",
    Object1Defaults = DefaultPermissions.Add | DefaultPermissions.Edit,
    Object2Defaults = DefaultPermissions.Add | DefaultPermissions.Edit
});

public class Role {
    public string Name { get; set; }
    public DefaultPermissions Object1Defaults { get; set; }
    public DefaultPermissions Object2Defaults { get; set; }
}

[Flags]
public enum DefaultPermissions {
    Add = 1 << 0,
    Edit = 1 << 1,
    Remove = 1 << 2
}

Of course, I'm also open to suggestions for better ways to implement permissions. 当然,我也乐于接受有关实现权限的更好方法的建议。 My plan was to have an enum for each other object in the database in the Role go off of that in each view just like with Object1Defaults and Object2Defaults except with better names and many more of them. 我的计划是在Role中的数据库中为每个其他对象提供一个枚举,就像使用Object1DefaultsObject2Defaults一样,在每个视图中都使用一个枚举,除了使用更好的名称以及更多名称。

First off, I'd recommend not using enums as Flags. 首先,我建议不要将枚举用作标志。 It limits how many you can have total, which may not be an issue now, but will be a big issue if you run out of bits later down the road. 它限制了您可以拥有的总数,这现在可能不是问题,但是如果您日后用完一点点将是一个大问题。 So make your permissions container a collection. 因此,使您的权限容器成为一个集合。

Once you do that, using linq, it's pretty easy to flatten the result into an array (or List, or whatever you want): 一旦这样做,就可以使用linq将结果展平为一个数组(或List或任何您想要的东西):

var result = roles.SelectMany(x => Object1Defaults).Distinct().ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM