簡體   English   中英

如何在C#中創建鏈接數組列表

[英]How to create Linked Array List in C#

我需要創建一個具有鏈接列表容量的數組。

基本上,我需要一個基於靜態索引的列表(如數組),但有可能獲取下一個和上一個字段(並輕松地在列表中來回循環和前進,就像使用鏈接列表一樣)。 注意:數組是二維的。 我使用自定義類作為數組值。 因此,我可以為每個實例設置上一個和下一個屬性。

有內置的C#集合嗎? 如果沒有,關於如何創建此版本的任何簡單建議? (我已經有一個版本,由2種方法組成。一種方法向前循環以設置前一個字段,而另一種方法向后循環以設置下一個字段,但仍然很麻煩。)

提前致謝

編輯:

問題是我對二維數組的使用。 如果遍歷我的數組:

            for (byte x = 0; x < Grid.GetLength(0); x++) 
            {
                for (byte y = 0; y < Grid.GetLength(1); y++) /
                {
                    //At certain point, I need to get the previous field. I can do:
                    if (y != 0)
                    {
                        y -= 2; //-2 because I will y++ in for. Already getting messy
                    }
                    else 
                    {
//What if y == 0? Then I can't do y--. I should get max y and  do x-- to get previous element:

                        y = (byte)(Grid.GetLength(1) - 1); //to get max value y

                        x--;
                    }
}
    }

有一個內置的LinkedList<T>類。

但是從您的描述來看,為什么數組不起作用? 它是靜態的,基於索引,您可以通過增加/減少索引來輕松獲取下一個和上一個元素。 很難從代碼中確切地看到您需要什么,但是我想指出,您可以使用以下方法輕松枚舉多維數組:

var arry = new int[2,3];
foreach(var item in arry)
{
    ...
}

因此,您可以將其與Stack<T>結構結合(將項目推入堆棧,然后將其彈出以獲得上一個)。

或者,您可以將數組直接轉換為LinkedList

var list = new LinkedList(arry.Cast<int>()); // flattens array

或者,要保留原始數組中的索引並仍將值作為鏈接列表循環遍歷,請使用:

var list = new LinkedList(arry.Cast<int>.Select((item, i) => new 
{ 
    Item = item, 
    Index1 = i % arry.GetLength(1), 
    Index2 = i / arry.GetLength(0) 
}));
var node = list.First;
while(node.Next != null)
{
    Console.WriteLine("Value @ {1}, {2}: {0}", node.Value.Item, node.Value.Index1, node.Value.Index2);
    // on some condition move to previous node
    if (...)
    {
        node = node.Previous;
    }
    else
    {
        node = node.Next;
    }
}

不,你沒有。 與其代替傳統陣列代替“智能鏈接節點陣列”(您正在朝着這個方向發展),不如嘗試在循環主體中添加幾個變量:

byte x_len = Grid.GetLength(0);
byte y_len = Grid.GetLength(1);
byte prev_x, next_x, prev_y, next_y;

for (byte x = 0; x < x_len; ++x) 
{
  prev_x = x == 0? x_len - 1 : x - 1;
  next_x = x == x_len - 1? 0 : x + 1;
  for (byte y = 0; y < y_len; ++y)
  {
    prev_y = y == 0? y_len - 1 : y - 1;
    next_y = y == y_len - 1? 0 : y + 1;

    // here, you have access to the next and previous
    // in both directions, satisfying your requirements
    // without confusing your loop variables.

  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM