Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing multiple enum values (Flagged): Reading in a filter type from a query string

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?

like image 953
Teeknow Avatar asked Dec 23 '13 04:12

Teeknow


People also ask

How to extract value from enum?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

What is enum parse?

The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.

When to use enum c#?

In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays. Monday is more readable then number 0 when referring to the day in a week.


1 Answers

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
like image 63
Adriaan Stander Avatar answered Dec 17 '22 00:12

Adriaan Stander