[英]Foreach Loop using KVP to iterate through a Multi-Dimensional List
我想使用一个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)之间的区别很重要的原因。 同样,如果我错了,请纠正我。
您不能使用KeyValuePair<>
,因为您没有枚举Dictionary<>
。 但您无需这样做,只需执行以下操作:
foreach(LogTable logTable in tablevars.loggingTable)
{
// do whatever with logTable.FunctionName and logTable.LogTime
}
更改您的foreach
以遍历List<LogTable>
foreach( LogTable lt in tablevars.loggingTable)
{...}
要么
使用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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.