0

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?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Wing Shum
  • 472
  • 6
  • 19
  • 2
    What about using [reflection](https://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-a-class) to get the properties or simply [serializing](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/) your object into a string, e.g in the JSON format. – devsmn Oct 01 '21 at 07:22

2 Answers2

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);
}
nyname00
  • 2,496
  • 2
  • 22
  • 25
1

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.

Marco
  • 22,856
  • 9
  • 75
  • 124