Foreach循环使用KVP迭代多维列表

时间:2014-11-26 14:13:29

标签: c# list foreach visual-studio-2013 keyvaluepair

我想使用foreach k,v对循环来运行多维列表,并将这些值输出到其他地方。这是代码:

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

当我在'foreach'上运行鼠标时,我收到一条警告说 - '无法将类型'DataObjects.LogTable'转换为'System.Collections.Generic.KeyValuePair。我该如何解决这个问题,或者是否有更有效的方法来实现同一目标?

谢谢!

我应该添加更多上下文,抱歉。我试图在属性'FunctionName'和'LogTime'中返回两个不同的值,我通过以下方式添加:

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

为了更准确地指定,foreach k,v循环的目的是获取FunctionName和LogTime的每个不同属性,并将它们输入到SQL Server中的数据库中。这就是k,v(或FunctionName,LogTime)之间的区别很重要的原因。如果我错了,请再次纠正我。

2 个答案:

答案 0 :(得分:1)

您无法使用KeyValuePair<>,因为您没有枚举Dictionary<>。但你不需要,只需这样做:

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

答案 1 :(得分:0)

更改foreach以迭代List<LogTable>

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

OR

使用KeyValuePair代替创建课程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 
}