简体   繁体   中英

How to use enum as value of the dictionary?

Is there any way to do next, see example:

I have enum with Filters:

enum SearchFilters
{   
      Id,
      ItemsPerPage
};

enum ReportFilters
{
     Name,
     Age
};

And enum with pages:

enum Pages
{
     Search,
     Report
};

Is there any way to do something like this:

Dictionary<string, enum> filters = new Dicionary<string, enum>()
{
   {Pages.Search.ToString(), SearchFilters},
   {Pages.Report.ToString(), ReportFilters}
};

And use it like:

filters[Pages.Search.ToString()].  <--- and here will appear the list of enum values.

For example you can use a value of SearchFilters enum:

filters[Pages.Search.ToString()].ItemPerPage

Any ideas?

Thanks.

You can do something like this. But I don't think the idea of having different enums in the same dictionary is good.

Dictionary<Pages, Type> filters = new Dictionary<Pages, Type>()
{
    {Pages.Search, typeof(SearchFilters)},
    {Pages.Report, typeof(ReportFilters)}
};

var arr = Enum.GetValues (filters [Pages.Report]);

You have to either use Dictionary<string, Array> :

var filters = new Dictionary<string, Array>()
    {
        { "Search", Enum.GetValues(typeof(SearchFilters)) }
    };

filters["Search"].Length; // 2. 
filters["Search"].Cast<SearchFilters>().Count(); // 2

or just store Type in Dictionary<string, Type> :

    var filters = new Dictionary<string, Type>()
    {
        { "Search", typeof(SearchFilters) }
    };

Enum.GetValues(filters["Search"]).Length; // 2

You cannot keep two different types in one dictionary (except you box-unbox the type). I'd suggest to keep the Key as enum Page and value as List<string> .

Then you can create following extension for enum:

public static List<string> ToMemberList(this Enum enumerationValue)
        {
            var type = enumerationValue.GetType();
            return Enum.GetValues(type).Cast<object>().Select(x => x.ToString()).ToList();
        }

And use it this way to create your dictionary:

var dit = new Dictionary<Pages, List<string>>()
                              {
                                  { Pages.Search, SearchFilters.Id.ToMemberList() },
                                  { Pages.Report, ReportFilters.Age.ToMemberList() }
                              };

var x1 = dit[Pages.Search];

Here x1 contains list of values in SearchFilters as string.

Note: Remember to keep the extension method inside a static class.

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