Determining the currently pointed to item in a list

后端 未结 2 1453
借酒劲吻你
借酒劲吻你 2021-01-21 20:59

I am working with lists. I have been able to determine the first and last position of items in my list. I am using getPostion and displaying item name through a

2条回答
  •  忘掉有多难
    2021-01-21 21:15

    I'm not sure if this solves Your issue, but You can add

    public fruit_trees current_tree;
    

    field in ListForTrees class.

    Then, You can easily add method showing next and moving item pointer to the next item in the list. Remembering the current item allows You to avoid browsing the whole list each time You want next tree from the list. The code can look like this:

    public fruit_trees GetNextTree()
    {
        //save currently pointed tree
        fruit_trees tree = this.current_tree;
        if (tree != null)
        {
            //move current_tree to the next tree, to be returned next time
            current_tree = current_tree.next_tree;
            //return saved tree object
        }
        return tree;
    }
    

    In order to make it work, You should also remember to initiate the value of current_tree with the first tree added to the list. You can also write some kind of ResetNextTreePointer() method pointing it back to the first tree in the list.

    Some more suggestions to the code:

    • I suppose it would be better to use properties for fields in your classes, so i.e. change

      public fruit_trees first_tree;
      

      into

      private fruit_trees first_tree;
      public fruit_trees First_tree { get { return first_tree; }
      

      as it would disable any class outside your class to modify those fields explicitly.

    • This code:

      if (count == 0)
      {
          ...
      }
      else if (count != 0)
      {
          ...
      }
      

      can be changed into:

      if (count == 0)
      {
          ...
      }
      else
      {
          ...
      }
      

提交回复
热议问题