c# - Enum to dictionary and format each name -
i need convert enum dictionary , after format each name (value) of dictionary.
public static dictionary<int, string> enumtodictionary<tk>(func<tk, string > func) { if (typeof(tk).basetype != typeof(enum)) throw new invalidcastexception(); return enum.getvalues( typeof(tk)) .cast<int32>() .todictionary( currentitem => currentitem => enum.getname(typeof(tk), currentitem)) /*. func each name */; } public enum types { type1 = 0, type2 = 1, type3 = 2 } public string formatname(types t) { switch (t) { case types.type1: return "mytype1"; case types.type2: return "mytype2"; case types.type3: return "mytype3"; default: return string.empty; } } after need this:
var resultedandformateddictionary = enumtodictionary<types>(/*delegate formatname() each element of dictionary() */); how define , implement delegate (func<object, string > func), performs action each value of dictionary?
update: correspoding result is
var = enumtodictionary<types>(formatname); //a[0] == "mytype1" //a[1] == "mytype2" //a[2] == "mytype3"
guessing question want achieve create dictionary enum enum value int key , formatted name value, right?
well, first function pass in should take tk argument, shouldn't it?
second, throwing invalidcastexception seems bit strange. invalidoperationexception might more appropriate (see this question)
third todictionary quite close:
public static dictionary<int, string> enumtodictionary<tk>(func<tk, string> func) { if (typeof(tk).basetype != typeof(enum)) throw new invalidoperationexception("type must enum"); return enum.getvalues(typeof(tk)).cast<tk>().todictionary(x => convert.toint32(x), x => func(x)); } now can call this:
public enum types { type1 = 0, type2 = 1, type3 = 2 } public string formatname(types t) { switch (t) { case types.type1: return "mytype1"; case types.type2: return "mytype2"; case types.type3: return "mytype3"; default: return string.empty; } } var resultedandformateddictionary = enumtodictionary<types>(formatname);
Comments
Post a Comment