首页 > 解决方案 > 遍历 IList在 ASP.NET MVC 中按索引

问题描述

我在遍历IList<Hashtable>. 我正在尝试按索引迭代它,即:

我有一个IList<Hashtable>有 3 个不同Hashtable的 s。我希望foreach每个都按IList's 索引。例如:

我首先要在index=0中的foreach所有KeyValuePairs 。完成后做一些事情,然后在index=1 中的所有s等等,直到所有s 都被迭代。目前代码如下:HashtableIListforeachKeyValuePairHashtableIListHashtable

变量data是一个IList<Hashtable>3Hashtable秒。

foreach (Hashtable rowData in data[index])
{
    some code here...
}

我收到以下错误:

无法将“System.Collections.DictionaryEntry”类型的对象转换为“System.Collections.Hashtable”类型。

标签: c#asp.net-mvc

解决方案


如果您想通过索引器操作符遍历一个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

推荐阅读