I have some enums like this:
internal enum CompanyA
{
workerA = 21,
workerB = 42,
}
internal enum CompanyB
{
workerC = 22,
workerD = 44,
}
internal enum CompanyA_Do
{
DoA = 11,
DoB = 5,
}
internal enum CompanyB_Do
{
DoA = 15,
DoB = 55,
}
I want to use the Environment.UserName to find out in which company the worker is employed.
If the Environment.UserName == workerA, then the company would be companyA.
Further, if isDoA == true, i want to get the int value from CompanyA_Do.DoA (value = 11). Or if isDoB == true and the worker is an employee from CompanyA, then i want the value from CompanyA_Do.DoB (value = 5).
I could iterate through the enum CompanyA and CompanyB and do some if-statements to get the right value.
foreach (string employee in CompanyA.GetNames(typeof(CompanyA)))
{
if (employee == Environment.UserName)
{
IsCompanA = true;
if (isDoA) workerDoValue = (int) CompanyA_Do.DoA
else if (isDoB) workerDoValue = (int) CompanyA_Do.DoB
break;
}
}
But i think this is messy solution. Especially, when i have 3 companies and plentiy of worker. I need a loop for every company.
I wonder, if there is a more elegant approach to get the int-value from CompanyX_Do.
CodePudding user response:
I don't think you are using the correct level of abstraction. If your enums instead described the actual values of each type, like:
internal enum Company
{
A,
B,
}
internal enum Do
{
A,
B,
}
you can create mappings using dictionaries like
public Dictionary<string, Company> WorkerToCompany = new (){
{"workerA", Company.A},
{"workerC" , Company.B},
}
public Dictionary<(Company, Do), int> CompanyToDoValue = new (){
{(Company.A, Do.A), 11},
{(Company.A, Do.B), 5},
{(Company.B, Do.B), 55},
}
Allowing you to write logic like
public int GetDoValue(string workerName, Do do){
var company = WorkerToCompany[workerName];
return CompanyToDoValue[(company, do)];
}
Note that using booleans, isDoA
/ isDoB
has an obvious problem in that both can be either true or false, what should the value be in these cases? You may also need error handling to handle things like if the worker does not have a dictionary entry.