如何使用多个循环在IList集合中递增
本文关键字:集合 IList 何使用 循环 | 更新日期: 2023-09-27 18:25:16
我有以下函数调用:
public static MvcHtmlString NavLinks(
this HtmlHelper helper,
IList<MenuItem> menuItems) {
在这个功能中,我知道我可以使用以下内容循环浏览菜单项
foreach (MenuItem menuItem in menuItems) {
<code here>
}
但我需要做的是同时使用outer和内部循环显示顶部菜单的一些代码,然后显示作为每个顶部菜单项一部分的子菜单项的代码。
所以每次menuItem.Enter的值发生变化时,我都想做一些操作,然后继续读取不同menuItem.Inter的记录,直到Outer循环的值再次发生变化。
下面是我的数据的一个示例。我只显示了两列,其中第1列表示menuItem。外部和第2列表示menuItems。内部
样本数据
.....
00 - do outer loop open action A
01 - do inner loop open action B
02 - do inner loop close action C, open action B
10 - do inner loop close action C, outer loop close action D and outer loop open action A
11 - do inner loop open action A
12 - do inner loop close action C, open action B
....
....
"no more data" - do inner loop close action C, outer loop close action D
....
操作:
action A that needs executing when the outer loop starts
action D that needs executing when the outer loop ends
action B that needs executing when the inner loop starts
action C that needs executing when the inner loop ends
有没有一种简单的方法可以在不使用foreach的情况下做到这一点?
您可以使用GroupBy扩展方法:
foreach (var group in menuItems.GroupBy(item => item.Outer))
{
// begin outer menu "group.Key"
foreach (var item in group)
{
// inner menu "item.Inner"
}
// end outer menu
}