Быть в состоянии показать следующее значение в связанном списке, нажав кнопку - PullRequest
1 голос
/ 18 марта 2019

Вероятно, это простая задача, но я не могу ее решить.

Итак, в настоящее время я настроил форму, которая содержит текстовое поле и кнопку, и я хочу иметь возможность нажимать кнопку, и первое значение в LinkedList будет отображаться в текстовом поле. Если я снова нажму кнопку, появится следующее значение и т. Д.

В настоящее время я делаю так, чтобы появилось первое значение, но затем я не могу перейти к следующему значению.

Это код, который у меня сейчас есть:

public class Node
{
    public string data;
    public Node next;
    public Node(string newData)
    {
        data = newData;
        next = null;
    }

    public void AddEnd(string data)
    {
        if (next == null)
        {
            next = new Node(data);
        }
        else
        {
            next.AddEnd(data);
        }
    }
}

public class myList
{
    public void AddEnd(string data)
    {
        if (headnode == null)
        {
            headnode = new Node(data);
        }
        else
        {
            headnode.AddEnd(data);
        }
    }

    public string getFirst() // this gets the first value within the list and returns it
    {
        if (headnode == null)
        {
            throw new Exception("List is empty");
        }

        Node node = headnode;
        while (node.next != null)
        {
         node = node.next;   
        }
        return node.data;
    }

Я также пытался использовать это:

public class NavigationList<T> : List<T>
{
    private int _currentIndex = -1;
    public int CurrentIndex
    {
        get
        {
            if (_currentIndex == Count)
                _currentIndex = 0;
            else if (_currentIndex > Count - 1)
                _currentIndex = Count - 1;
            else if (_currentIndex < 0)
                 _currentIndex = 0;

            return _currentIndex;
        }
            set { _currentIndex = value; }
    }

    public T MoveNext
    {
        get { _currentIndex++; return this[CurrentIndex]; }
    }
        public T Current
    {
        get { return this[CurrentIndex]; }
    }
}

Однако я не очень знаком с чем-то подобным, поэтому не знал, как его использовать.

1 Ответ

0 голосов
/ 19 марта 2019

Итак, у вас есть последовательность предметов, и единственное, что вам нужно, это получить первый предмет, и как только вы получаете предмет, каждый раз, когда вы его запрашиваете, вы хотите следующий предмет, пока больше ничего не осталось.

В .NET это называется IEnumerable, или, если вы знаете, какие элементы находятся в вашей последовательности, например, элементы MyClass, это называется IEnumerable<MyClass>. В вашем случае вам нужен IEnumerable<string>.

К счастью .NET загружен классами, которые реализуют IEnumerable. Два из наиболее часто используемых - массив и список. Вам редко приходится создавать перечислимый класс самостоятельно, повторно использовать существующие и перечислять его.

List<string> myData = ... // fill this list somehow.

IEnumerator<string> myEnumerator = null // we are not enumerating yet.

string GetNextItemToDisplay()
{    // returns null if there are no more items to display

     // if we haven't started yet, get the enumerator:
     if (this.myEnumerator == null) this.myEnumerator = this.myData.GetEnumerator();

     // get the next element (or if we haven't fetched anything yet: get the first element
     // for this we use MoveNext. This returns false if there is no next element
     while (this.myEnumerator.MoveNext())
     {
          // There is a next string. It is in Current:
          string nextString = enumerator.Current();
          return nextString;
     }

     // if here: no strings left. return null:
     return null;
}

Это выглядит как много кода, но если вы удалите комментарии, это всего лишь несколько строк кода:

string GetNextItemToDisplay()
{
     if (this.myEnumerator == null) this.myEnumerator = this.myData.GetEnumerator();
     while (this.myEnumerator.MoveNext())
          return enumerator.Current();
     return null;
}

Ваш обработчик событий ButtonClick:

void OnButtonClick(object sender, eventArgs e)
{
     string nextItemToDisplay = this.GetNextItemToDisplay();
     if (nextItemToDisplay != null)
        this.Display(nextItemToDisplay);
     else
        this.DisplayNoMoreItems():
}

Если вы хотите начать заново с первого элемента, например, после изменения списка

void RestartEnumeration()
{
    this.myEnumerator = null;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...