Loop through object properties without reflection

I have class MyModel and some object of MyModel.

I need for-loop or foreach properties of object without reflection. How implemented?

Class example:

public class MyModel
{
    public string Level1_TypeName { get; set; }
    public string Level1_AttrType { get; set; }
    public string Level1_AttrValue { get; set; }
    public string Level2_TypeName { get; set; } 
    public string Level2_AttrType { get; set; }
    public string Level2_AttrValue { get; set; }
    public string Level3_TypeName { get; set; } 
    public string Level3_AttrType { get; set; }
    public string Level3_AttrValue { get; set; }
    public string Level4_TypeName { get; set; } 
    public string Level4_AttrType { get; set; }
    public string Level4_AttrValue { get; set; }
    public string Level5_TypeName { get; set; } 
    public string Level5_AttrType { get; set; }
    public string Level5_AttrValue { get; set; }
    public string Level6_TypeName { get; set; }  
}
Jon Skeet
people
quotationmark

I would strongly suggest that you take two actions:

  • Create a new type to encapsulate the combination of TypeName, AttrType, AttrValue
  • Change your model to contain a collection of that class rather than several separate properties.

At that point, it will be really easy to iterate over the properties without using reflection... and your code will be much clearer, too.

people

See more on this question at Stackoverflow