Append Loop Variable to Variable Name

前端 未结 3 1532
夕颜
夕颜 2021-01-26 05:04

I have 5 DataTables that needs to be converted to TXT files. Instead of creating them separately, I thought I use a for loop. Here\'s my code:

Strin         


        
相关标签:
3条回答
  • 2021-01-26 05:46

    You cannot just append a number to a variable name at runtime to magically reference a new variable. What you should do instead is:

    Define an an interface:

    public interface IFileBLO
    {
        DataTable SelectFileForCSV();
    }
    

    Have File1BLO, File2BLO etc all implement IFileBLO and fix the method names so that they are all SelectFileForCSV rather than SelectFile1ForCSV etc.

    Add a lookup for reference these objects:

    var bloList = new IFileBLO[]
    {
        file1BLO, file2BLO, file3BLO, file4BLO, file5BLO
    };
    

    Finally, change your loop to:

    for (int i = 0; i < 5; i++)
    {
        var dtFile = bloList[i].SelectFileForCSV();
        foreach (var dr in dtFile.Rows)
        {
            ...
    
    0 讨论(0)
  • 2021-01-26 06:00

    There are not enough information in the question to know exactly what the problem is, so I'm just guessing here. Your problem is that you have five objects, that all have a method, and these method have different names. The methods return the same thing, though, DataTable, that can be used in a loop.

    If that's the case then just take out of the loop that which is different, so that in the loop remains that which is identical. Something like this:

    DataTable[] fiveTables =
    {
        file1BLO.SelectFile1ForCSV(),
        file2BLO.SelectFile2ForCSV(),
        file3BLO.SelectFile3ForCSV(),
        file4BLO.SelectFile4ForCSV(),
        file5BLO.SelectFile5ForCSV()
    }
    
    for (int i = 1; i <= 5; i++)
    {
        // Use fiveTables[i] for DataTable, and i for file name
    }
    
    0 讨论(0)
  • 2021-01-26 06:05

    Use this:

    Response.AddHeader("content-disposition", "attachment;filename=CAPRES-FILE"
                + i
                + "-"
                + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".txt");
    

    This will create a filename containing the value of i.

    0 讨论(0)
提交回复
热议问题