使用foreach循环遍历Map集合,使key值和vaule值对应输出

 我来答
北京京彩化妆学校
2015-12-15 · 北京就业最好的化妆培训学校
北京京彩化妆学校
北京京彩化妆摄影美甲学校是集化妆、美甲、摄影、数码设计为一体的专业培训学校,是目前国内就业最好的培训学校!
向TA提问
展开全部
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Myforeach
{
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p[0] = "宝马";
p[1] = "奥迪";
p[2] = "阿斯顿马丁";
//for (int i = 0; i < p.Count; i++)
//{
// Console.WriteLine(p[i]);
//}

//任何类型,只要想使用foreach来循环遍历,就必须在当前类型中
//存在: public IEnumerator GetEnumerator()方法,(一般情况我们会通过实现IEnumerable接口,来创建该方法。)
foreach (string item in p)
{
Console.WriteLine(item);
}

//IEnumerator etor = p.GetEnumerator();
//while (etor.MoveNext())
//{
// string str = etor.Current.ToString();
// Console.WriteLine(str);
//}
Console.ReadKey();

}
}

public class Person : IEnumerable
{
private List<string> listCar = new List<string>();

public int Count
{
get
{
return this.listCar.Count;
}

}

public string this[int index]
{
get
{
return listCar[index];
}

set
{
if (index >= listCar.Count)
{
listCar.Add(value);
}
else
{
listCar[index] = value;
}
}
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public string Email
{
get;
set;
}

#region IEnumerable 成员

//这个方法的作用不是用来遍历的,而是用来获取一个对象
//这个对象才是用来遍历的。
public IEnumerator GetEnumerator()
{
return new PersonEnumerator(listCar);
}

#endregion
}

//这个类型,的作用就是用来遍历Person中的List集合的。
public class PersonEnumerator : IEnumerator
{
public PersonEnumerator(List<string> _cars)
{
cars = _cars;
}

//这个字段中存储的就是Person对象中的listCar集合
private List<string> cars;

//假设一开始遍历的对象的索引是-1
private int index = -1;

#region IEnumerator 成员

//表示获取当前正在遍历的那个对象
public object Current
{
get
{
if (index < 0)
{
return null;
}
return cars[index];
}
}
//让自定义下标index累加
public bool MoveNext()
{
index = index + 1;
if (index >= cars.Count)
{
return false;
}
else
{
return true;
}
}

public void Reset()
{
index = -1;
}

#endregion
}
}
分享
千锋教育
2016-01-08 · 做真实的自己 用良心做教育
千锋教育
千锋教育专注HTML5大前端、JavaEE、Python、人工智能、UI&UE、云计算、全栈软件测试、大数据、物联网+嵌入式、Unity游戏开发、网络安全、互联网营销、Go语言等培训教育。
向TA提问
展开全部

代码如下:

<c:forEach items="${map}" var="test">
     <c:forEach items="${test.value}" var="value">
         ${value.name}
     </c:forEach>
     <br>
</c:forEach>
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
id415161761
2013-06-13 · 超过11用户采纳过TA的回答
知道答主
回答量:35
采纳率:0%
帮助的人:32.8万
展开全部
使用Iterator遍历岂不更方便

Set entries = map.entrySet( );
if(entries != null) {
Iterator iterator = entries.iterator( );
while(iterator.hasNext( ))
{Map.Entry entry =iterator.next( );
Object key = entry.getKey( );
Object value = entry.getValue();;....}
}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(1)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式