Search code examples
c#listfield-names

How to get the field names of a list inside foreach?


I have the following class:

public class ListOfVariablesToSave : List<List<int>>
{
    public List<int> controlDB { get; set; }
    public List<int> interacDB { get; set; }

    public ListOfVariablesToSave()
    {
        controlDB = new List<int> { 1, 2, 3 };
        interacDB = new List<int> { 21, 22, 23 };

        Add(controlDB);
        Add(interacDB);
    }
}

and the following code to write its content to a text file:

ListOfVariablesToSave myListOfVariablesToSave = new ListOfVariablesToSave();

StreamWriter myFile = new StreamWriter("fileName.txt");
foreach (List<int> DB in myListOfVariablesToSave)
{
    foreach (int varToSave in DB)
    {
        myFile.WriteLine(varToSave);
    }
}
myFile.Close();

What I get is:

1
2
3
21
22
23

What I would like to get is:

controlDB
1
2
3
interacDB
21
22
23

Is it possible to do this by perhaps just adding a single line of code after the first foreach?


Solution

  • I would think about doing something like this:

    public class ListOfVariablesToSave : List<ListOfThings<int>>
    {
        public ListOfThings<int> controlDB { get; set; }
        public ListOfThings<int> interacDB { get; set; }
    
        public ListOfVariablesToSave()
        {
            controlDB = new ListOfThings<int>() { 1, 2, 3  };
            controlDB.Name = "controlDB";
            interacDB = new ListOfThings<int>() { 21, 22, 23 };
            interacDB.Name = "interacDB";
    
            Add(controlDB);
            Add(interacDB);
        }
    
    }
    
    public class ListOfThings<T> : List<T>
    {
        public string Name { get; set; }
    
        public ListOfThings() : base() { }
    }
    

    Instead of your ListOfVariablesToSave being derived from List<List<int>> you instead create another class that derives from List<int> and adds your name property.

    You can then iterate like this:

    var lists = new ListOfVariablesToSave();
    foreach (var list in lists) 
    {
        Console.WriteLine(list.Name);
        foreach (var i in list)
        {
            Console.WriteLine(i);
        }
    }