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\$
1
  • \$\begingroup\$ This is looking much nicer and much simpler. \$\endgroup\$
    – Nick Udell
    Commented Jan 29, 2015 at 9:28

1 Answer 1

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\$
3
  • \$\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
    Commented Jan 29, 2015 at 3:38
  • \$\begingroup\$ @Hosch250 ah, in that case you can just write CurrentItem = ItemList.First(...). \$\endgroup\$
    – mjolka
    Commented Jan 29, 2015 at 3:43
  • \$\begingroup\$ Already did it.. \$\endgroup\$
    – user34073
    Commented Jan 29, 2015 at 3:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.