简体   繁体   中英

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

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.

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   
}

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 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM