c# - 遍历 IList在 ASP.NET MVC 中按索引
问题描述
我在遍历IList<Hashtable>
. 我正在尝试按索引迭代它,即:
我有一个IList<Hashtable>
有 3 个不同Hashtable
的 s。我希望foreach
每个都按IList
's 索引。例如:
我首先要在index=0中的foreach
所有KeyValuePair
s 。完成后做一些事情,然后在index=1 中的所有s等等,直到所有s 都被迭代。目前代码如下:Hashtable
IList
foreach
KeyValuePair
Hashtable
IList
Hashtable
变量data
是一个IList<Hashtable>
3Hashtable
秒。
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}");
}
}
Hashtable 的参考包含 DictionaryEntry 项。
输出将是这样的:
a = b
c = d
e = f
g = h
或者那个:
a = b
e = f
c = d
g = h
推荐阅读
- c++ - C++ 神经网络实现 XOR.Output 总是接近 0.5
- javascript - Javascript/React Native 循环仅将变量更新为最后一个值
- traefik - 路径的 Traefik basicauth
- c# - VS2015:Microsoft.CSharp.Core.targets(67,5):错误MSB6004:指定的任务可执行位置“...\csc”无效
- php - Laravel - 运行播种机时在 Guzzle 函数中抛出异常
- javascript - var module = require() 还是 const {module} = require()?
- python - 将 for 循环转换为 numpy 数组
- sql - 为什么在导入 CSV 时在 postgresql 中出现“整数类型的输入语法无效”?
- python - 如何在 Pygame 中播放随机 Mp3 文件
- gradle - Gradle - 从测试模块运行应用程序