2010-07-20 58 views
3

我有一個小麻煩搞清楚如何調用Parallel.ForEach用二維數組的字符串:如何調用Parallel.ForEach與多維數組

string[,] board = new string[,]{ 
     {"A", "B", "C", "D", "E" }, 
     {"F", "G", "H", "I", "J"}, 
     {"K", "L", "M", "N", "O"}, 
     {"0", "1", "2", "3", "4"}}; 

Parallel.ForEach(board, row => 
    { 
     for (int i = 0; i < row.Length; ++i) 
     { 
      // find all valid sequences 
     } 
    }); 

如果我沒有明確指定類型我得到以下錯誤:

The type arguments for method 'System.Threading.Tasks.Parallel.ForEach(System.Collections.Generic.IEnumerable, System.Action)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

什麼是明確指定類型參數的正確方法?

回答

6

您的問題在於二維數組不能實現IEnumerable<one-dimensional-array>。 (它確實實現IEnumerable,但它的字符串「變平」的陣列的IEnumerable)。你可以做兩件事情:

  • 更改string[,]的鋸齒狀陣列的陣列,string[][]

  • 實現您自己的擴展方法,該方法遍歷二維數組並將其變成一個IEnumerable<one-dimensional-array>

+0

啊...的*鋸齒*陣列的工作! – Kiril 2010-07-20 01:16:49

+0

@Link:另外,如果性能足以讓這個平行,那麼你會想要使用鋸齒狀的數組,因爲它們更有效率地索引。 – 2010-07-20 01:25:34

+0

@Brian Gideon:我覺得這很奇怪。在適當的情況下(例如在長時間運行的獨立操作的情況下),並行化可以使性能發生重大變化。出於性能原因將多維數組轉換爲鋸齒形數組是我稱之爲微優化的原因。 – 2010-07-20 01:41:32

3

您應該仍然能夠使這項工作有一個多維數組,只是用Parallel.For代替Parallel.ForEach

string[,] board = new string[,] { 
    {"A", "B", "C", "D", "E" }, 
    {"F", "G", "H", "I", "J"}, 
    {"K", "L", "M", "N", "O"}, 
    {"0", "1", "2", "3", "4"} 
}; 

int height = board.GetLength(0); 
int width = board.GetLength(1); 

Parallel.For(0, height, y => 
    { 
     for (int x = 0; x < width; ++x) 
     { 
      string value = board[y, x]; 
      // do whatever you need to do here 
     } 
    } 
); 
+0

這也是個好主意!謝謝! – Kiril 2010-07-20 01:30:13