C# 记录哈希表属性
我有一个C# 记录哈希表属性,c#,visual-studio-2012,C#,Visual Studio 2012,我有一个哈希表,我正试图为其记录值。哈希表的名称为“props”。 我的代码如下: Dictionary<string, string> keyPairs = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> items in props) { keyPairs.Add(items.Key, items.Value); }
哈希表
,我正试图为其记录值。哈希表的名称为“props”。
我的代码如下:
Dictionary<string, string> keyPairs = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> items in props)
{
keyPairs.Add(items.Key, items.Value);
}
Logging.Instance.WriteInformation(string.Format("Key: {0} \t Value: {1}", keyPairs.Keys, keyPairs.Values));
等等
另外,在调试中,异常似乎发生在foreach循环的开始处。我还尝试将其设置为KeyValuePair
,但我得到了相同的InvalidCastException。
这可能与KeyValuePair
位于System.Collections.Generic内部和Hashtable
位于System.Collections内部有关吗?当然,只需循环:
for (var entry : keyPairs)
{
Logging.Instance.WriteInformation(string.Format("Key: {0} \t Value: {1}",
entry.Key, entry.Value);
}
它只有几行-如果您需要在多个位置使用它,您可以轻松地将其放入方法中。在循环时记录
Dictionary<string, string> keyPairs = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> items in props)
{
keyPairs.Add(items.Key, items.Value);
Logging.Instance.WriteInformation(string.Format("Key: {0} \t Value: {1}", items.Key, items.Value));
}
字典键对=新字典();
foreach(道具中的KeyValuePair项)
{
添加(items.Key、items.Value);
Logging.Instance.WriteInformation(string.Format(“Key:{0}\t Value:{1}”、items.Key、items.Value));
}
您可以使用循环,或者,如果您需要单行程序:
var allPairs = string.Join(Environment.NewLine,
keyPairs.Select(kvp => string.Format("Key: {0} \t Value: {1}", kvp.Key, kvp.Value)));
Logging.Instance.WriteInformation(allPairs);
我最初避免这样做的原因是,Logging.Instance.WriteInformation
的工作方式是将单个条目放入文件中,因此我希望将所有键/值保存在一个文件中entry@wjhguitarman-你能通过重载WriteInformation()来获取字典吗?然后您可以在内部(使用循环)将其格式化为单个日志条目。LINQ类似于Tim Schmelter.:)LINQ工作得很好,结果发现问题出在foreach循环中,一旦我更改了类型,它就消失了,LINQ帮助保持了一切的简洁。谢谢大家的帮助!
var allPairs = string.Join(Environment.NewLine,
keyPairs.Select(kvp => string.Format("Key: {0} \t Value: {1}", kvp.Key, kvp.Value)));
Logging.Instance.WriteInformation(allPairs);