-1

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; }
    ...
Tom Xue
  • 3,169
  • 7
  • 40
  • 77
  • 3
    Change your DataModel, so that it contains a single List or an array of strings, instead of those 17 members. – Clemens Mar 23 '22 at 17:05
  • this looks kinda crazy :D why don't you save the filenames in a List ? – Martin Bartolomé Mar 23 '22 at 17:06
  • 3
    possible with Reflection, but likely not a good choice (depends on use). – hijinxbassist Mar 23 '22 at 17:06
  • 1
    To bring home the previous comments, what if you need FileName18 down the road? Or FileName999? – Eric J. Mar 23 '22 at 17:10
  • This is why the programming gods invented arrays so you definitely **do not** have this situation with `.FilenameXX`. The sane solution would be `.Filename` to be an array or collection. Step 1. fix `DataModel` not to use this pattern. – JAlex Mar 23 '22 at 17:18
  • As an alternative you could create a `Dictionary` and create the key by `FileName` + index of the array and then set the value you need. Then you can always pull out what you need by the key. Here's a quick example https://dotnetfiddle.net/H4VtiZ – Trevor Mar 23 '22 at 18:32

2 Answers2

0
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.

0

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

Charles Yang
  • 330
  • 2
  • 10