如何在foreach循环中获取ArrayList中字典的键和值

3
我想循环遍历一个包含字典的ArrayList。
foreach(Dictionary<string, string> tempDic in rootNode) 
{ 
    Response.Write(tempDic.key + "," tempDic.value + "<br>"); 
} 

如何访问字典的键和值?

1
“字典键和值”是什么意思?字典有多个键和值。 - StriplingWarrior
2个回答

4

您还需要在字典内部循环,为此,您可以使用Foreach迭代tempDic

foreach(Dictionary<string, string> tempDic in rootNode) 
{
    foreach(KeyValuePair<string, string> _x in tempDic)
    {
        Response.Write(_x.key + "," + _x.value + "<br>");
    }
}

但是ArrayList只有12行,其中一行只有一个字典,但使用2个foreach将打印出约62行数据。 - hkguile

0

你可以首先使用LINQ获取一个包含所有KeyValuePair的列表(实际上是 IEnumerable<KeyValuePair<string, string>>):

var pairs = rootNode.OfType<Dictionary<string, string>>()
                    .SelectMany(d => d.AsEnumerable());
foreach (KeyValuePair<string, string> tempPair in pairs)
{
    Response.Write(tempPair.Key + "," + tempPair.Value + "<br>");
}

所以,只需要做一个foreach循环就足够了。另一个循环将由LINQ为您完成。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接