views:

190

answers:

3

hey, I have two-dimension array

 List<List<int>> boardArray

How can I enumerate throw this array to check that it contains other value than 0 ? I think about boardArray.Contains and ForEach ,cause it return bool value but I don't have too much experience with lambda expression :/ Please help :)

+3  A: 
if (!boardArray.SelectMany(list => list).All(i => i == 0)) {
  ...
}

SelectMany flattens the List<List<int>> into one sequence of ints, whereas All checks that every element matches a condition.

Julien Lebosquain
I like your use of `SelectMany`, however Anthony's use of `Any` and checking for non-zero is superior to using `All` and checking for zero. `Any` will stop looping as soon as it finds a value other than zero, while `All` will keep going even after it has enough information to answer the question, "Is there a non-zero value?"
Joel Mueller
They're the exact opposite and work in the same way. `All` will stop as soon as it find a value that is not zero. So `All()` is the same as `!Any()` and `Any()` is the same at `!All()`. Reflector both if you want to see it by yourself.
Julien Lebosquain
@Joel: Julien is correct here - `All(i => i==0)` will return false as soon as it finds any non-zero value, at the same place as `Any(i => i!=0)` would return true. The only extra cost here is the single extra negation, which is hardly worth considering.
tzaman
Apologies for the brain-fart. I guess I was looking at `All` and thinking of a Where/Count situation.
Joel Mueller
+2  A: 

Do you want to check the inner lists or simply the entire thing for a non-zero?

boardArray.Any(list => list.Any(item => item != 0));
boardArray.Where(list => list.Any(item => item != 0));

The first line will return true/false indicating whether or not there is any list within the outer list that has a non-zero value. The second line, on the other hand, filters for the lists containing non-zero items.

Anthony Pegram
Thanks, your lambda is the fastest. This I'm looking for ;)
netmajor
A: 

bool containsZero = (!boardArray.SelectMany(list => list).Any(i => i == 0))

This says From all the items in boardarray loop through all of the items inside of that and return faslse if one isn't zero, then we are inversing that false.

msarchet