简体   繁体   中英

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. 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. How do I flatten the collection?

Here's some example code from my LINQPad test:

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.

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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