Allow multiple options to be selected mapped to int instead of binary flags

0

I want to create a DisplayMode for a control, that filters the data that shows up in it. The types that feed into the control come from a database, and have an ID that is used to filter the list.

What I'd like to do:

enum ItemType 
{
    None = 0,
    All = ~0,
    Option1 = 1 << 0,
    Option2 = 1 << 1,
    Option3 = 1 << 2,
}

[Flags]
enum DisplayModeEnum
{
    None = ItemType.None,
    All = ItemType.All,
    Option1 = ItemType.Option1,
    Option2 = ItemType.Option3,
    Option3 = ItemType.Option3,
    Options2And3 = ItemType.Option2 | ItemType.Option3
}

Retreiving data:

var filteredResults = AllItems.Where(x => this.DisplayMode.HasFlag((DisplayModeEnum)x.AlertType));

This way, I can specify things like "Options2And3", or I could specify multiple display modes "Option1,Option2" and it will work as expected.

However, in reality, ItemType will just be an int, and will have ordinal values (1, 2, 3, etc) instead of 1 << 0 (0x0000001). Therefore, the [Flags]DisplayModeEnum wouldn't work correctly the way I am using it above. (Example: if I tried to encode the act of selecting int's 1 and 3, the resulting logical or would give me 0x00000011, which could either mean 2, 3, or 1 and 3, and is therefore not usable)

Question: Is there an elegant way of coding this so I can select multiple options like you can do with [Flags] but the selected values are ordinal integers instead of binary flags?

Alternative I've considered

I've considered doing it this way, but it seems inelegant compared to using the [Flags] attribute on an enum. Storing a mapping in a dictionary:

enum DisplayModeEnum
{
    None,
    All,
    Option1,
    Option2,
    Option3,
    Options2And3,
}

var mapping = new Dictionary<DisplayModeEnum, List<int>>(){
   {DisplayMode.None, null},
   {DisplayMode.All, new List<int>() {1,2,3,4,5,6}},
   {DisplayMode.Option1, new List<int>() {1}},
   {DisplayMode.Options2And3, new List<int>() {2,3}},
};

Receiving data:

var filteredResults = AllItems.Where(x => mapping[this.DisplayMode].Contains(x.ItemTypeID));

What I don't like about this is that this limits me so I could only enable one preset DisplayMode, instead of being able to able to create a new one on the fly. (Say I want to show options 1 and 3, but DisplayModeEnum doesn't have [Flags] so I can't, so if I want to show a custom combination of options, I have to create a new DisplayModeEnum option for the exact configuration I want.

This also means I have to edit the Dictionary with int IDs instead of being able to refer to an enum.

c#
collections
enums
asked on Stack Overflow Feb 11, 2014 by DLeh • edited Feb 11, 2014 by DLeh

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0