Samantha J T Star
Samantha J T Star

Reputation: 32788

How can I increment through an IList collection with more than one loop

I have the following function call:

public static MvcHtmlString NavLinks(
            this HtmlHelper helper,
            IList<MenuItem> menuItems) {

Within this function I know I can use the following to cycle through the menuItems

   foreach (MenuItem menuItem in menuItems) {
       <code here>
   }

But what I need to do is to go through the menuItems list with both an outer and an inner loop to show some code for the top menu and then code for the sub menu items that are part of each top menu item.

So every time the value of menuItem.Outer changes I want to do some action and then keep reading records with different menuItem.Inner until the values of Outer loop changes again.

Here's an example of what my data looks like. I just show two columns where Column 1 represents menuItem.Outer and column 2 represents menuItem.Inner

Sample data

.....
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
....

The actions:

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

Is there a simple way that I could do this without using foreach?

Upvotes: 0

Views: 216

Answers (1)

dtb
dtb

Reputation: 217293

You can use the GroupBy Extension Method:

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
}

Upvotes: 1

Related Questions