0

This is tenuously related to C#: How do i assign many variables with an integer(i) in for loop?.

Basically, I have an entity with properties Category1Results, Category2Results, Category3Results... etc up to Category60Results. There are also around 15 other properties. These map to a database table.

Is there a sensible way to assign to these?

A loop seems like it might be helpful, where (for example) the property with name Entity.Category+i+Result is assigned to, but I'm not sure how one would achieve that.

Any advice?

Community
  • 1
  • 1
Rich
  • 162
  • 3
  • 11

1 Answers1

0

You could do this with reflection. Take a look at this post where Jon Skeet provides a solution to assign an objects properties.

for(int i = 1; i <= 60; i++)
{
   SetProperty(entity, "Category"+i+"Result", valueYouWantToAssign)
}

Here is another example that loops through the properties of the object.

PropertyInfo[] properties = typeof(MyClass).GetProperties();
foreach(PropertyInfo property in properties)
{
    property.SetValue(instanceOfMyClass, attribute.DataValue, null);
}
Community
  • 1
  • 1
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
  • Thanks a lot for this. I've gone with the first method, which works well. I would have thought that the latter option is the more elegant, but it requires a bit of tinkering in my code and I'm just looking for a quick fix for now. Thanks again! – Rich Dec 13 '10 at 14:13