linq用于所有的二维数组

时间:2012-07-16 03:16:13

标签: c# linq

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

我有上面的二维数组。

我需要检查3件事,首先是检查所有单元格是否像上面一样填充。

第二

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

对于上面的数组,我需要检查每行是否填充了所有单元格。

第三

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

我想查找是否填充了第一列的第一个元素。

我可以使用foreach循环或循环来完成。但我想将All(predicate)与linq一起使用。

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

                foreach (var value in ticketValue)
                {

                }
            } 

最好的方法是什么?

1 个答案:

答案 0 :(得分: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?[]>();
}

希望这就是你想要的......