我有以下代码,它输出导航栏的一系列链接:
<% foreach (var item in (Dictionary<string, string>)ViewData["navItems"])
{
Response.Write(Html.ActionLink(item.Key, item.Value));
}
%>
是否有办法更改此代码,以便以相反的顺序输出链接列表?
最佳答案
您可以使用Enumerable.Reverse
方法(文档here):
var dic = (Dictionary<string, string>)ViewData["navItems"];
foreach (var item in dic.Reverse())
{
Response.Write(Html.ActionLink(item.Key, item.Value));
}
或者老式的解决方案:将 foreach 循环更改为 for 循环,从最后一项开始,递减索引..
关于asp.net - ASP MVC - 反转 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13210121/