2011-12-09 32 views
4

給我有類型,其長度和寬度是均勻的,但深度爲鋸齒狀的3D地圖:拼合一個三維陣列的體積爲對象的一維數組

public class Map<T> 
{ 
    T[,][] map; 
    ... 
} 

什麼是最好的方式返回由2D區域定義的體積內的所有類型對象以及該區域內的所有深度的一維數組。

public IEnumerable<T> this[Rectangle area] 
{ 
    get {...} 
} 

或只是

public IEnumerable<T> this[int x, int y, int width, int length] 
{ 
    get {...} 
} 

我誠實地希望一個快速LINQ解決方案,但性能是最好的解決方案視覺優雅:舉例如下,我可能有一個數組符號覆蓋。返回的扁平數組內的對象的順序不重要。如果有人有任何建議或經驗,請分享你的智慧。

另外,如果有另一個數據結構可以執行我不知道的相同功能,我會很樂意使用它。

如果有關於我的問題的內容不清楚,請詢問更多詳情。

回答

1

這可能會實現,以及(不LINQ)

public IEnumerable<T> this[int x, int y, int width, int length] 
    { 
     get 
     { 
      for (int i = 0; i < length; i++) 
      { 
       for (int j = 0; j < width; j++) 
       { 
        for (int k = 0; k < map[x + i, y + j].Length; k++) 
        { 
         yield return map[x + i, y + j][k]; 
        } 
       } 
      } 
     } 
    } 
+0

這個解決方案和LINQ解決方案都很好,這個比LINQ有一個小的性能提升,這就是爲什麼我給你答案。 – LamdaComplex

2

你在找這樣的事嗎?

public IEnumerable<T> this[int left, int top, int width, int height] 
{ 
    get 
    { 
     return from x in Enumerable.Range(left, width) 
       from y in Enumerable.Range(top, height) 
       from i in this.map[x, y] 
       select i; 
    } 
} 
+0

這個解決方案的偉大工程,但比稍慢for循環的解決方案。只是輕微。當遍歷4700x4700區域時,此解決方案的計時時間爲3.4秒,for循環解決方案爲1.7秒。 – LamdaComplex

相關問題