algorithm - Create a List of objects using enum data C# -


so have enum:

public enum myenum {     ibm = 1,     hp = 2,     lenovo = 3 } 

i have brand class

public class brand {     public brand(string name, int id)     {         name = name;         id = id;     }      public string name { get; private set; }     public int id { get; private set; } } 

i want create list of brand objects populated data myenum. like:

private ienumerable<brand> brands = new list<brand> {     new brand(myenum.ibm.tostring(), (int) myenum.ibm),     new brand(myenum.hp.tostring(), (int) myenum.hp),     new brand(myenum.lenovo.tostring(), (int) myenum.lenovo), }; 

i can create 2 arrays - 1 enum names , other enum ids , foreach them create brand object every iteration wonder if there better solution.

finally, going royi mindel solution according me appropriate . many daniel hilgarth answer , making royi mindel suggestion work. give credit both of them question if could.

public static class enumhelper {     public static ienumerable<valuename> getitems<tenum>()          tenum : struct, iconvertible, icomparable, iformattable     {         if (!typeof(tenum).isenum)             throw new argumentexception("tenum must enumeration type");          var res = e in enum.getvalues(typeof(tenum)).cast<tenum>()                   select new valuename() { id = convert.toint32(e), name = e.tostring() };          return res;     } }  public struct valuename {     public int id { get; set; }     public string name { get; set; } } 

i suggest making general valuename class fit enums , not make specific classes fit specific enums

public static class enumhelper {     public static ienumerable<valuename> getitems<tenum>()          tenum : struct, iconvertible, icomparable, iformattable     {         if (!typeof(tenum).isenum)             throw new argumentexception("tenum must enumeration type");          var res = e in enum.getvalues(typeof(tenum)).cast<tenum>()                     select new valuename() { value = convert.toint32(e), name = e.tostring()};          return res;     }  }  public struct valuename {     public int value { get; set; }     public string name { get; set; } } 

then :

enumhelper.getitems<myenum>() 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -