Foreach Loop using KVP to iterate through a Multi-Dimensional List

670 views Asked by At

I want to use a foreach k, v pairs loop to run through a multidimensional list, and output those values elsewhere. Here is the code:

public class LogTable
{
    public string FunctionName { get; set; }
    public string LogTime { get; set; }
}

public class TableVars
{
    public List<LogTable> loggingTable { get; set; }
    public TableVars()
    {
        loggingTable = new List<LogTable>();
    }
    public void createLogList()
    {
        loggingTable = new List<LogTable>();
    }
}

foreach( KeyValuePair<string, string> kvp in tablevars.loggingTable)
{
    // output would go here. I haven't looked it up yet but I assume it's something 
    // along the lines of var = k var2 = v? Please correct me if I'm wrong.     
}

When I run my mouse over 'foreach' I get a warning saying - 'Cannot convert type 'DataObjects.LogTable' to 'System.Collections.Generic.KeyValuePair. How can I resolve this issue, or is there a more efficient way to accomplish the same goal?

Thanks!

I should have added more context, sorry. I'm trying to return the two different values inside the properties 'FunctionName' and 'LogTime' which I have added via:

var tablevars = new TableVars(); tablevars.loggingTable.Add(new LogTable { FunctionName = errorvalue, LogTime = logtime });

To specify more accurately, the intention of the foreach k, v loop was to grab every distinct property of FunctionName and LogTime and input them into a database in SQL Server. This is why the distinction between k, v (or FunctionName, LogTime) is important. Again, please correct me if I'm wrong.

2

There are 2 answers

0
Thomas Weller On BEST ANSWER

You cannot use KeyValuePair<>, because you don't enumerate a Dictionary<>. But you don't need to, simply do this:

foreach(LogTable logTable in tablevars.loggingTable)
{
    // do whatever with logTable.FunctionName and logTable.LogTime   
}
1
robasta On

Either change your foreach to iterate through List<LogTable>

foreach( LogTable lt in tablevars.loggingTable)
 {...}

OR

Use a KeyValuePair instead of creating class LogTable

public class TableVars
{
    public Dictionary<string,string> loggingTable { get; set; }
    public TableVars()
    {
        loggingTable = new Dictionary<string,string>();
    }
    public void createLogList()
    {
        loggingTable = new Dictionary<string, string>();
    }
}

foreach( KeyValuePair<string, string> kvp in tablevars.loggingTable)
{
    //loggingTagle is now a KeyValuePair 
}