2013-03-11 44 views
0

我需要創建一個具有鏈接列表容量的數組。基本上,我需要一個基於靜態索引的列表(如數組),但有可能獲得下一個和前一個字段(並且很容易通過鏈表向後和向前循環,就像使用鏈表一樣)。 注意:數組是二維的。我使用一個自定義類作爲數組值。所以我可以爲每個實例設置上一個和下一個屬性。如何在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--; 
        } 
} 
    } 

回答

4

有一個內置的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; 
    } 
} 
+0

因爲我使用的是2維陣列。我將放置代碼片段並在我的答案中解釋問題,而不是在這裏。 Ty :) – dylanmensaert 2013-03-11 19:53:33

+0

謝謝。它看起來像我在解釋非常糟糕:(正如代碼中所解釋的(或至少tryed),我需要通過列表動態循環前進,這是我無法做到的(見代碼中的註釋)與2D陣列 – dylanmensaert 2013-03-11 20:19:44

+0

@ user1933169好的,我已經更新了我的答案,我想我已經提供了一個適合您的需求的解決方案 – 2013-03-11 20:35:51

2

不,你不知道。相反,以代替「智能連接節點陣列」,這是什麼,似乎像你對標題的放棄傳統陣列,儘量只在您的循環體中添加一些變量:

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. 

    } 
} 
+0

這可能是一個很好的答案,但我很不熟悉您使用的語法 – dylanmensaert 2013-03-11 20:37:41

+0

@ user1933169'?:'是[條件或三元運算符](http://msdn.microsoft.com/en-us/library/ty67wk28(v = vs.80).aspx)。 – 2013-03-11 20:38:59

+0

k,將會看進入它Tyvm – dylanmensaert 2013-03-11 20:51:30