我在迭代IList<Hashtable>
时遇到一些问题。我正试图通过索引进行迭代,即:
我有一个IList<Hashtable>
,里面有3个不同的Hashtable
。我想按IList
的索引来foreach
。例如:
我想首先foreach
IList
索引=0中Hashtable
中的所有KeyValuePair
。完成后,做一些事情,然后foreach
,IList
索引=1中Hashtable
中的所有KeyValuePair
s,依此类推,直到所有Hashtable
s都迭代完成。目前的代码如下:
变量data
是一个包含3个Hashtable
s的IList<Hashtable>
foreach (Hashtable rowData in data[index])
{
some code here...
}
我得到以下错误:
无法将类型为"System.Collections.DictionaryEntry"的对象强制转换为类型为"System.Collections.Hashtable".
如果您想通过索引器操作符迭代IList<HashTable>
:
IList<Hashtable> data = new List<Hashtable>
{
new Hashtable { { "a", "b"} },
new Hashtable { { "c", "d"}, {"e", "f"} },
new Hashtable { { "g", "h"} },
};
然后您可以执行以下操作:
//Iterate through the IList but interested only about the index
foreach (var index in data.Select((_, idx) => idx))
{
//Iterate through the Hashtable which contains DictionaryEntry elements
foreach (DictionaryEntry rowData in data[index])
{
Console.WriteLine($"{rowData.Key} = {rowData.Value}");
}
}
哈希表的引用包含DictionaryEntry项。
输出为:
a = b
c = d
e = f
g = h
或者说:
a = b
e = f
c = d
g = h
试试这个代码
foreach(Hashtable rowData in data)
{
foreach(DictionaryEntry pair in rowData)
{
Console.WriteLine($"{pair.Key} {pair.Value}");
}
}