skip to Main Content

I have a Model that is filled with 20 Properties, for instance such as

public class SensorModel
{
    public string Trigger1 { get; set; }
    public string PathDoor1 { get; set; }
    public string PathDoor2 { get; set; }
    public string PathTrigger1 { get; set; }
    public string PathTrigger2 { get; set; }
    public string PathTrigger3 { get; set; }
    public string PathTrigger4 { get; set; }
    public string PathTrigger5 { get; set; }
    public string PathTrigger6 { get; set; }
    public string PathTrigger7 { get; set; }
    public string PathTrigger8 { get; set; }
}  

After declaring and setting their properties by doing such,

SensorModel sensorsData = new SensorModel();

How can I access sensorsData‘s properties using a loop?

Because I would like to logs all the data into a txt along with DateTime, I find manually accessing is a waste of time.

Is there any way to automate, for instance, using a loop and accessing it one by one?

2

Answers


  1. You can use reflection to achieve this:

    var obj = new SensorModel();
    // ...
    
    // Get all the properties of your class
    var props = typeof(SensorModel).GetProperties();
    foreach (var prop in props)
    {
       // Get the "Get" method and invoke it
       var propValue = prop.GetGetMethod()?.Invoke(obj, null);
       // Do something with the value
       Console.Out.WriteLine("propValue = {0}", propValue);
    }
    
    Login or Signup to reply.
  2. You can use reflection to achieve your goal:

    var model = new SensorModel() {
        PathDoor1 = "Foo",
        PathDoor2 = "Foo2",
        PathTrigger1 = "Value of PT1",
        PathTrigger2 = "Value of PT2",
    };
    
    foreach(var value in model.GetTriggerValues()) {
        Console.WriteLine(value);
    }
    
    
    public class SensorModel
    {
    
        public string Trigger1 { get; set; }
        public string PathDoor1 { get; set; }
        public string PathDoor2 { get; set; }
        public string PathTrigger1 { get; set; }
        public string PathTrigger2 { get; set; }
        /* ... */
    
        public IEnumerable<string> GetTriggerValues() {
            foreach(var prop in this.GetType().GetProperties().Where(x => x.Name.StartsWith("PathTrigger"))) {
                yield return (string)prop.GetValue(this, null);
            }
        }
    
    }
    

    This example filters your properties by name, if you want or need a different result set, amend or remove the where clause.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search