Home > Enterprise >  How to reference variable name which contains number in a loop
How to reference variable name which contains number in a loop

Time:03-24

My code is below. dm is the instance of my Class DataModel, and it contains 17 member vaiable (string). formatted is a string array, it is easy to use it in a loop. But as for dm.FileName, which needs be assigned value in the loop, how to reference them in a loop?

        dm.FileName1 = formatted[0] ?? "";
        dm.FileName2 = formatted[1] ?? "";
        dm.FileName3 = formatted[2] ?? "";
        dm.FileName4 = formatted[3] ?? "";
        dm.FileName5 = formatted[4] ?? "";
        dm.FileName6 = formatted[5] ?? "";
        dm.FileName7 = formatted[6] ?? "";
        dm.FileName8 = formatted[7] ?? "";
        dm.FileName9 = formatted[8] ?? "";
        dm.FileName10 = formatted[9] ?? "";
        dm.FileName11 = formatted[10] ?? "";
        dm.FileName12 = formatted[11] ?? "";
        dm.FileName13 = formatted[12] ?? "";
        dm.FileName14 = formatted[13] ?? "";
        dm.FileName15 = formatted[14] ?? "";
        dm.FileName16 = formatted[15] ?? "";
        dm.FileName17 = formatted[16] ?? "";

    public string FileName1 { get; set; }
    public string FileName2 { get; set; }
    public string FileName3 { get; set; }
    ...

CodePudding user response:

Update your DataModel:

public List<String> FileNames {get; set;}

Then where you want to assign values of formatted to your dm:

dm.FileNames.AddRange(formatted);

This just adds all values in formatted to FileNames

CodePudding user response:

for(int i = 1; i < 18; i  )
{
    Type type = DataModel.GetType();
    PropertyInfo prop = type.GetProperty("Filename"   i);
    prop.SetValue(target, propertyValue, null);
}

Something like this perhaps?

Set object property using reflection

You could also make the filenames be contained in a list, which would be significantly eaiser.

  •  Tags:  
  • c#
  • Related