So I’m pulling some information out of a database and I need to map it to my model’s properties. My first attempt at this yielded a large switch statement which is following an obvious pattern. I am wondering if this fragile code can be expressed in a more dynamic fashion.
foreach (AttributeValue attributeValue in attributeValues)
{
string label = attributes.First(a => a.ID == attributeValue.AttributeID).Name;
switch (attributeValue.AttributeName)
{
case "TaskSequence":
TaskSequenceLabel = label;
break;
case "TaskStatus":
TaskStatusLabel = label;
break;
case "InstallChangeNumber":
InstallChangeNumberLabel = label;
break;
case "InstallChangeStart":
InstallChangeStartLabel = label;
break;
case "InstallChangeEnd":
InstallChangeEndLabel = label;
break;
case "SubmittedDateTime":
SubmittedDateTimeLabel = label;
break;
case "InstalledDateTime":
InstalledDateTimeLabel = label;
break;
}
}
Basically what I am thinking is “Map labels to properties which have the label’s value + “Label””
You can do that with reflection: