1

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 :)

2
  • This is not an area but a List of List<int>. Commented May 26, 2010 at 19:28
  • This is not an array -.- Now is there an answer to the actual question ? Commented Sep 30, 2013 at 7:59

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your lambda is the fastest. This I'm looking for ;)
4
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.

4 Comments

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?"
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.
@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.
Apologies for the brain-fart. I guess I was looking at All and thinking of a Where/Count situation.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.