I have a list of strings like:
public string TypeOrig { get; set; }
public string TypeAdj { get; set; }
public string TypeClass { get; set; }
public string TypeMsg { get; set; }
public string QtyOrig { get; set; }
public string QtyAdj { get; set; }
public string QtyClass { get; set; }
public string QtyMsg { get; set; }
Based on the row from the db, I populate the strings like this:
switch(fRow["fieldName"].ToString())
{
case "partType":
TypeOrig = fRow["original"].ToString();
TypeAdj = fRow["adjusted"].ToString();
TypeClass = fRow["status"].ToString();
TypeMsg = fRow["message"].ToString();
break;
case "qty":
QtyOrig = fRow["original"].ToString();
QtyAdj = fRow["adjusted"].ToString();
QtyClass = fRow["status"].ToString();
QtyMsg = fRow["message"].ToString();
break;
}
I would like to reduce this to something like this:
switch(fRow["fieldName"].ToString())
case "partType": fieldName = "Type";
break;
case "qty": fieldName = "Qty";
break;
}
fieldName + "Orig" = fRow["original"].ToString();
fieldName + "Adj" = fRow["adjusted"].ToString();
fieldName + "Class" = fRow["status"].ToString();
fieldName + "Msg" = fRow["message"].ToString();
Additional Information:
- There are a few exceptions from the field name in the db, so I cannot simply use the field name and have to use the switch.
- I also have to populate some non-standard strings for a couple of the fields from the db.
- I currently have 32 field names and that can grow, so reducing the length of code will make it so much easier to manage. (@Servy’s approach reduced it down to 19)
- The resulting strings are used in the view.
How do I dynamically set the string name and populate it?
You should refactor your object. Whenever you see yourself prefixing a bunch of fields/properties with the same thing it often manes you should be creating a new type to represent that kind of data.
Now back to your first type we can have:
Now that we have two objects of the same type we can separeate out the code for populating the object and placing that object in
MyClass: