2012-07-16 49 views
2
[0,0,0] 
[1,1,1] 
[2,2,2] 

我有上面的2維數組。linq for 2維陣列與所有

我需要檢查3件事情,首先檢查是否所有單元格都像上面一樣填充。

第二:

[0,0,0] 
[1] 
[] 

對於上述陣列,我需要檢查是否所有的細胞每行填充。

三:

[0,] 
[1,1] 
[2,2,2] 

我想找如果填充第一列的第一要素。

我可以用foreach循環或for循環來做到這一點。但我想用linq的All(predicate)

  foreach (var ticketValue in ticketValues) 
      { 
       firstRow = ticketValue.All(x => x == i); 

       foreach (var value in ticketValue) 
       { 

       } 
      } 

這樣做的最好方法是什麼?

+6

我不確定你到底想要做什麼。你可以列出預期的產出還是寫出你想要做的'foreach'版本? – 2012-07-16 04:43:33

+1

你的意思是說3維數組嗎? – chridam 2012-07-16 13:04:19

+0

可能會給出一些代碼示例,因爲您的描述非常模糊。我認爲第一個數組是一些樣本數據[不是數組聲明],但第二個例子是FUBAR?一個行元素* NOT *如何從給定的[int,2d數組] * *必須填充的描述中填充。 – NPSF3000 2012-07-16 13:18:08

回答

3

我假設你正在建立的是2D這樣的:

int?[][] myArrayA = new int?[][] { new int?[] {0,0,0}, new int?[] {1,1,1}, new int?[] {2,2,2} }; 
int?[][] myArrayB = new int?[][] { new int?[] {0,0,0}, new int?[] {1}, new int?[] {null} }; 
int?[][] myArrayC = new int?[][] { new int?[] {0,null}, new int?[] {1,1,1}, new int?[] {2,2,2} }; 

因此,使用LINQ我們這樣做:

bool FirstCheck(int?[][] theArray) 
{ 
    int size = (from arrays in theArray select arrays.GetUpperBound(0)).Max(); 

    var check = from arrays in theArray 
       where theArray.All(sub => sub.GetUpperBound(0) == size) 
       select arrays; 

    return size + 1 == check.Count<int?[]>(); 
} 

bool SecondCheck(int?[][] theArray) 
{ 
    int size = (from arrays in theArray select arrays.GetUpperBound(0)).Max(); 

    var check = from arrays in 
        (from subs in theArray 
        where theArray.All(sub => sub.All(value => value != null)) 
        select subs) 
       where arrays.GetUpperBound(0) == size 
       select arrays; 

    return size + 1 == check.Count<int?[]>(); 
} 

bool ThirdCheck(int?[][] theArray) 
{ 
    int size = (from arrays in theArray select arrays.GetUpperBound(0)).Max(); 

    var check = from arrays in theArray 
       where theArray.All(array => array[0].HasValue) 
       select arrays; 

    return size + 1 == check.Count<int?[]>(); 
} 

希望這是你在想什麼?

+0

謝謝盟友。讚賞。 – DarthVader 2012-07-17 16:57:04