4
\$\begingroup\$

So I received a comment on my previous question that suggested creating a Dictionary of my menus to store the data in. So that got me thinking, all I am doing is going back to the first instance of MenuItem in the ItemList that has a Menu of Back[0].Menu. So why not just iterate through there and open the menu when I find it?

So, here is my final code:

public void GoBack()
{
    NavButtonUsed = true;

    Forward.Insert(0, Back[0]);
    Back.RemoveAt(0);

    if (Back[0].Title.StartsWith(" ") && CurrentItem.Menu != Back[0].Menu)
    {
        foreach(MenuItem mi in ItemList)
        {
            if (mi.Menu == Back[0].Menu)
            {
                CurrentItem = ItemList[ItemList.IndexOf(mi)];
                break;
            }
        }
    }

    CurrentItem = ItemList[ItemList.IndexOf(Back[0])];
    NavButtonUsed = false;
}

Everything else stayed the same as in my previous question, please check that for details.

\$\endgroup\$
  • \$\begingroup\$ This is looking much nicer and much simpler. \$\endgroup\$ – Nick Udell Jan 29 '15 at 9:28
6
\$\begingroup\$

CurrentItem = ItemList[ItemList.IndexOf(mi)];

can just be

CurrentItem = mi;

You could also use FirstOrDefault:

var item = ItemList.FirstOrDefault(i => i.Menu == Back[0].Menu);
if (item != null)
{
    CurrentItem = item;
}
\$\endgroup\$
  • \$\begingroup\$ Good points. It is guaranteed that it will never be null in my particular case - it it was, more than one thing would be broken. \$\endgroup\$ – user34073 Jan 29 '15 at 3:38
  • \$\begingroup\$ @Hosch250 ah, in that case you can just write CurrentItem = ItemList.First(...). \$\endgroup\$ – mjolka Jan 29 '15 at 3:43
  • \$\begingroup\$ Already did it.. \$\endgroup\$ – user34073 Jan 29 '15 at 3:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy