[英]Create circular doubly linked list
我有下一個代碼:
static LinkedList<Entry> items = new LinkedList<Entry>();
public static Entry runner;
Entry
是一個存儲來自數據庫行的信息的結構。
使用下一個 function 我將Entry
添加到列表中:
public void Prepare()
{
// Makes connection to DB
while(dbReader.Read())
{
Entry entry = new Entry(item1, item n);
items.AddLast(entry);
}
runner = items.First.Value;
}
然后我調用一個 function,它正確地將該runner
的值設置為 window 上的圖形元素。
使用兩個按鈕,我可以在該列表上向前和向后移動,同時正確更新所有圖形項,但以下情況除外:
我將如何解決這個問題? 我想讓它表現為一個循環雙向鏈表。
我知道System.Collections.Generic
的LinkedList
作為單/正常/經典雙向鏈表工作。
這是按鈕的代碼:
private void previousButton()
{
runner = items.Find(runner).Previous.Value;
// Call function to set items<node> to graphical elements
}
nextButton()
的工作原理完全相同,但使用Next
而不是Previous
。
我已經嘗試過runner = items.Find(runner).Previous.Value?? items.Last.Value;
runner = items.Find(runner).Previous.Value?? items.Last.Value;
正如這里所建議的那樣,但它說的是?? operator cannot be asigned to types 'Entry' & 'Entry'
?? operator cannot be asigned to types 'Entry' & 'Entry'
。
在Prepare()
更改runner = items.First.Value;
只是runner = items.First();
沒什么區別。
進入 class 而不是結構,您將能夠按預期在其上使用 null 合並運算符。 由於您在 LinkedList 中存儲對 Entry 實例的引用,因此您可能會從 class 獲得比結構更好的性能(除非您非常需要結構語義)。
我不確定您為什么不使用在 C# 中創建循環鏈接列表的答案中提供的確切代碼?
盡管如此,您可以通過添加?
空條件運算符。 這是因為Previous
可能是null
,這將是使用??
合並到null
的基礎。 .
runner = items.Find(runner).Previous?.Value ?? items.Last.Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.