C#: Create a generic method that can return an enum as List<string> -


how can create generic method receives enum type , return values , names in list of strings, loop list , each iteration ill able print each of enum values, example, consider next pseudo:

enum myenum { a=5, b=6, c=8 }  list<string> createenumstrings(anyenum(??)) {   list<string> listresult;    // ??   // code generate:   // listresult[0] = "value 5 name a"   // listresult[1] = "value 6 name b"   // lsitresult[2] = "value 8 name c"    return listresult; } 

again, note method can type of enum

public list<string> getvalues(type enumtype) {     if(!typeof(enum).isassignablefrom(enumtype))         throw new argumentexception("enumtype should describe enum");      var names = enum.getnames(enumtype).cast<object>();     var values = enum.getvalues(enumtype).cast<int>();      return names.zip(values, (name, value) => string.format("value {0} name {1}", value, name))                 .tolist();      } 

now if go with

getvalues(typeof(myenum)).foreach(console.writeline); 

will print:

value 5 name value 6 name b value 8 name c 

non-linq version:

public list<string> getvalues(type enumtype) {        if(!typeof(enum).isassignablefrom(enumtype))         throw new argumentexception("enumtype should describe enum");      array names = enum.getnames(enumtype);     array values = enum.getvalues(enumtype);      list<string> result = new list<string>(capacity:names.length);      (int = 0; < names.length; i++)     {         result.add(string.format("value {0} name {1}",                                  (int)values.getvalue(i), names.getvalue(i)));     }      return result; } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -