1

I'm trying to loop through a row of data for a set amount of times to access a different property every time.

The data looks like this:

    [JsonProperty("Afbeelding")]
    public string Afbeelding { get; set; }

    [JsonProperty("Afbeelding_2")]
    public string Afbeelding2 { get; set; }

    [JsonProperty("Afbeelding_3")]
    public string Afbeelding3 { get; set; }

    [JsonProperty("Afbeelding_4")]
    public string Afbeelding4 { get; set; }

    [JsonProperty("Afbeelding_5")]
    public string Afbeelding5 { get; set; }

    [JsonProperty("Afbeelding_6")]
    public string Afbeelding6 { get; set; }

    [JsonProperty("Afbeelding_7")]
    public string Afbeelding7 { get; set; }

I've tried the folllowing in the loop:

var path = CreateFile(profitImageRow.("Afbeelding"+i), profitImageRow.Bestandsnaam+i);

The first one does not compile while the second one only adds i to the value of "Bestandsnaam"

Is there any way to make this work in a loop?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Possible duplicate of [Get property value from string using reflection in C#](https://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – mjwills Dec 27 '17 at 12:24

1 Answers1

0

First of all, it would seem that your JSON should've been deserialized as Dictionary<string, string>, and then the Key would be your _X properties and values would also be there.

If you can't (or won't) change the model, you can use the powers of reflection.

E.g.

var props = typeof(MyModel).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.Name.StartsWith("Afbeelding"));

foreach(var prop in props)
{
  var value = prop.GetValue(modelHere); //now value has the corresponding string.
}

// Or you can do
for(int i =1 ; i < 8; i++){
  var neededProp = props.FirstOrDefault(x => x.Name == $"Afbeelding_{i}"); //now this has the value
}
zaitsman
  • 8,984
  • 6
  • 47
  • 79