2013-06-26 27 views
0

如何在數組c#中運用布爾運算符。 我有三個相同大小的3D數組,我想對兩個數組施加布爾運算符並將結果保存在數組3中。 例如:如何在數組中使用布爾運算符?

int[, ,] array1 = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
          { { 7, 8, 9 }, { 10, 11, 12 } } }; 
int[, ,] array2 = new int[,,] { { { 1, 1, 1 }, { 0, 0, 0 } }, 
          { { 0, 0, 0 }, { 0, 0, 0 } } }; 
int [, ,] array3 = new int[4,3]; 
result = array1 (AND operator) array2; 

預期的結果:

array3 = { { 1, 2, 3 }, { 0, 0, 0 } },{ { 0, 0, 0 }, { 0, 0, 0 } }; 

我的問題是沒有什麼辦法來實現布爾施加兩個陣列,而無需訪問數組元素?

謝謝您的提前。

+1

你是說你想屏蔽第一個數組? –

+0

是的,掩蓋(不是很好地表達了問題) – Michael

+0

&&是邏輯運算符,它返回true或false,除了3 && 1返回3嗎? – 2013-06-26 08:27:18

回答

2

好消息是從框架4.0有Zip method

Enumerable.Zip方法應用於指定 函數兩個序列,其 生成結果的一個序列的相應的元件。

對於一維數組是簡單的:

 int[] array1 = new int[] { 1, 2, 3 }; 
     int[] array2 = new int[] { 0, 1, 0 }; 

     var zipped = array1.Zip(array2, (first, second) => second == 0 ? 0 : first); 
     //zipped = {0, 2, 0} 

壞消息是,多維數組不實現IEnumerable,但你可以使用壓縮與鋸齒狀排列。你可以嘗試這樣的事情:

 int[][] jagged1 = new int[][] 
       { 
        new int[] {1,2,3}, 
        new int[] {4,5,6}, 
        new int[] {7,8,9} 
       }; 

     int[][] jagged2 = new int[][] 
       { 
        new int[] {1,1,1}, 
        new int[] {0,0,0}, 
        new int[] {0,0,0} 
       }; 

     var zipped = jagged1.Zip(jagged2, (firstArray, secondArray)        
         => firstArray.Zip(secondArray, 
           (first, second) => second == 0 ? 0 : first) 
        ); 

     //zipped = {{1,2,3}, {0,0,0}, {0,0,0}} 
1

我不能完全明白你的意思,但是:

int[,,] array3 = new int[array1.GetLength(0), array1.GetLength(1), array1.GetLength(2)]; 

for (int x = 0; x < array1.GetLength(0); ++x) 
    for (int y = 0; y < array1.GetLength(1); ++y) 
     for (int z = 0; z < array1.GetLength(2); ++z) 
      array3[x, y, z] = (array2[x, y, z] != 0) ? array1[x, y, z] : 0; 

如果數組2 [X,Y,Z]不爲零,設置ARRAY3 [X,Y,Z],以數組1 [X, y,z]否則將array3 [x,y,z]設置爲0.

這是你的意思嗎?