Question

I'm plan to make a page that displays info about user's in the form of a table. Each column will be a property of the table. I want someone viewing the table to be able to choose ways to filter the users. There will be two check boxes: 1 for reported users and 1 for creation date. I'm planning to make an enum called UserFilter like so:

public enum UserFilter
{
   None = 0,
   Date = 1,
   Reported = 2
}

If I need to add another type it's value will be set to 4 so that I can tell which enums are selected through a bitwise or (3 would be both 1 and 2). The problem I'm having is with reading in an enum from the query string. I guess I could do something like posting back with an int (0 for none, 1 for date, 2 for report, 3 for both) but I would like to try posting back with the actual string. I'm not sure how I would parse "Date|Reported" into an enum value that doesn't exist in UserFilter.

In a nutshell: Is there a clean way to parse "Date|Reported" into the value 3 without adding another value to my enum?

Was it helpful?

Solution

You could try something like

string enumString = "Date|Reported";
UserFilter uf = enumString.Split('|').ToList().Select(e =>
{
    UserFilter u;
    Enum.TryParse(e, true, out u);
    return u;
}).Aggregate((u, c) => u = u | c);

I would however recomend that you change your enum to

public enum UserFilter
{
    None = 1,
    Date = 2,
    Reported = 4
}

as if you have it your way None|Date is the same as Date, because 0 + 1 => 1

EDIT

As @ScottSelby stated, this would also work

UserFilter u = (UserFilter) 3;
//or 6 rather than 3 if you take my comment above into consideration
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top