I hope I can explain my problem in a way that it's clear for everyone. We need your suggestions on this.
We have an Enum Type which has more than 15 constants defined. We receive a report from a web service and translate its one column into this Enum type. And based on what we receive from that web service, we run specific functions using Dictionary
Why am I asking for ideas? Let's say 3 of these Enum contants meet specific functions in our Dictionary but the rest use the same function. So, is there a way to add them into our Dictionary in a better way rather than adding them one by one? I also want to keep this structure because when it's time, we might have specific functions in the future for the ones that I described as "the rest".
To be more clear here's an example what we're trying to do:
Enum:
public enum Reason{
ReasonA,
ReasonB,
ReasonC,
ReasonD,
ReasonE,
ReasonF,
ReasonG,
ReasonH,
ReasonI,
ReasonJ,
ReasonK
}
Defining our Dictionary:
public Dictionary<Reason, Action<CustomClassObj, string>> ReasonHandlers = new Dictionary<Reason, Action<CustomClassObj, string>>{
{ Reason.ReasonA, HandleReasonA },
{ Reason.ReasonB, HandleReasonB },
{ Reason.ReasonC, HandleReasonC },
{ Reason.ReasonD, HandleReasonGeneral },
{ Reason.ReasonE, HandleReasonGeneral },
{ Reason.ReasonF, HandleReasonGeneral },
{ Reason.ReasonG, HandleReasonGeneral },
{ Reason.ReasonH, HandleReasonGeneral },
{ Reason.ReasonI, HandleReasonGeneral },
{ Reason.ReasonJ, HandleReasonGeneral },
{ Reason.ReasonK, HandleReasonGeneral }
};
So basically what I'm asking is, is there a way to add Reason, Function pair more intelligently? Because as you can see after ReasonC, all other reasons use the same function.
Thank you for your suggestions.
You could try something like this, only put the custom Reason handler in the dictionary and then fallback to the General one.
public Dictionary<Reason, Action<CustomClassObj, string>> ReasonHandlers = new Dictionary<Reason, Action<CustomClassObj, string>>{
{ Reason.ReasonA, HandleReasonA },
{ Reason.ReasonB, HandleReasonB },
{ Reason.ReasonC, HandleReasonC }};
public Action<CustomClassObj, string> ReasonHandlerLookup (Reason reason) {
Action<CustomClassObj, string> result = null;
ReasonHandlers.TryGetValue(reason, out result);
return result ?? HandleReasonGeneral;
}
switch
unless you have some dynamic requirement - leppie 2012-04-05 17:22