protected Dictionary<string , string> xmlList = new Dictionary<string , string>();
protected System.Collections.ArrayList list = new System.Collections.ArrayList();
我已将字典存储在这样的arraylist中..
xmlList.Add( "image" , "images/piece1.png" );
xmlList.Add( "description" , " Experience why entertainment is more amazing with Xbox." );
xmlList.Add( "title" , "Downloads" );
list.Add( xmlList );
xmlList.Clear();
xmlList.Add( "image" , "images/piece2.png" );
xmlList.Add( "description" , "Limited-time offer: Buy Office now, get the next version free.*" );
xmlList.Add( "title" , "Security & Updates" );
list.Add( xmlList );
如何从arraylist访问字典的每个元素?
<% for (int i = 0; i < list.Count; i++)
{
foreach(Dictionary<string , string> itemList in list)
{
Response.Write( itemList["image"] );
}
}
%>
这给了我两次相同的结果'images / piece2.png'..
我无法做到
foreach(Dictionary<string , string> itemList in list[i])
{
Response.Write( itemList["image"] );
}
答案 0 :(得分:2)
protected Dictionary<string, string> xmlList;
protected System.Collections.ArrayList list = new System.Collections.ArrayList();
xmlList = new Dictionary<string, string>();
xmlList.Add("image", "images/piece1.png");
xmlList.Add("description", " Experience why entertainment is more amazing with Xbox.");
xmlList.Add("title", "Downloads");
list.Add(xmlList);
xmlList = new Dictionary<string, string>();
xmlList.Add("image", "images/piece2.png");
xmlList.Add("description", "Limited-time offer: Buy Office now, get the next version free.*");
xmlList.Add("title", "Security & Updates");
list.Add(xmlList);
foreach (Dictionary<string, string> itemList in list)
{
Response.Write(itemList["image"]);
Response.Write("<br>");
}
答案 1 :(得分:1)
1)使用通用List<T>
代替ArrayList
:
Dictionary<string, string> xmlList = new Dictionary<string, string>();
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
2)如果你想在列表中有两个单独的词典,你需要创建其中两个,否则你有两个引用同一个词典。所以:
list.Add(xmlList);
xmlList = new Dictionary<string, string>(); //instead of xmlList.Clear();
//...
list.Add(xmlList);
3)现在,您可以执行以下操作来遍历词典列表:
foreach (Dictionary<string, string> d in list)
{
//...
}
答案 2 :(得分:0)
您可以使用此代码段迭代列表中的每个字典并获取字典中的每个元素。
foreach(Dictionary<string,string> xdict in list)
{
foreach(var xkey in xdict.Keys)
{
Response.Write(xdict[xkey]);
}
}
答案 3 :(得分:0)
我觉得你正在使用相同的对象xmllist两次。这就是你获得图像两次的原因。请尝试xmllist1和xmllist2。迭代字典和arraylist的所有其他答案对我来说都是正确的。这就是可以的原因。所以请试试这个。
xmlList1.Add( "image" , "images/piece1.png" );
xmlList1.Add( "description" , " Experience why entertainment is more amazing with Xbox." );
xmlList1.Add( "title" , "Downloads" );
list.Add( xmlList1 );
xmlList2.Add( "image" , "images/piece2.png" );
xmlList2.Add( "description" , "Limited-time offer: Buy Office now, get the next version free.*" );
xmlList2.Add( "title" , "Security & Updates" );
list.Add( xmlList2 );
然后使用CodeIgnoto的方法。