Search code examples
c#.netwinformscircular-list

Create circular doubly linked list


I have the next code:

static LinkedList<Entry> items = new LinkedList<Entry>();
public static Entry runner;

Entry is a struct that stores information from a database row.

With the next function I add Entry items to the list:

public void Prepare()
{
    // Makes connection to DB
    while(dbReader.Read())
    {
        Entry entry = new Entry(item1, item n);
        items.AddLast(entry);
    }
    runner = items.First.Value;
}

Then I call a function that correctly sets the values of that runner to the graphic elements on a window.

With two buttons I am able to move forward and backwards on that list while updating all the graphic items correctly, except in the next cases:

  1. When trying to go to the previous node while being at the first node.
  2. When trying to go to the next node while being at the last one.

How would I solve this? I want to make it behave as a circular doubly linked list.
I know that System.Collections.Generic´s LinkedList works as a single/normal/classic doubly linked list.

This is the code of the buttons:

private void previousButton()
{
    runner = items.Find(runner).Previous.Value;
    // Call function to set items<node> to graphical elements
}

nextButton() works exactly the same but uses Next instead of Previous.

I already tried to do runner = items.Find(runner).Previous.Value ?? items.Last.Value; as suggested here, but it says that ?? operator cannot be asigned to types 'Entry' & 'Entry'.

On Prepare() changing runner = items.First.Value; to just runner = items.First(); makes no difference.


Solution

  • I'm not sure why you don't use the exact code provided in the answer at Creating a circularly linked list in C#?

    Be that as it may, you can fix your immediate problem by adding a ? null-conditional operator. This is because Previous might be null, and that would be the basis of coalescing to null using ??.

    runner = items.Find(runner).Previous?.Value ?? items.Last.Value;