1

What is the proper way to handle a 2D array with LINQ?

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

bool anyZeroes = array.Any(value => value == 0)     // example

I want to check if any variable in the array matches a Func, == 0 in this case. How can I use Any for this and what is the best practice here?

bytecode77
  • 14,163
  • 30
  • 110
  • 141
  • Does that code compile or is it supposed to indicate your intent? – evanmcdonnal Apr 13 '15 at 19:35
  • It's how I would want it to write. – bytecode77 Apr 13 '15 at 19:35
  • Alright. I'm pretty sure it doesn't work because the vector style array you got there (2D, whatever you want to call it) doesn't implement `IEnumerable`, meaning it's not possible. – evanmcdonnal Apr 13 '15 at 19:36
  • 1
    Yep... The question it duplicates explains. Personally I just avoid using `[ , ]` type of arrays altogether. I've never seen an example where they're more appropriate or useful than a `List` or an array of arrays. – evanmcdonnal Apr 13 '15 at 19:39
  • When you have a fixed size "grid", like in a 2D board game, what else should you use? A `List` misleadingly suggest that items can be added, which will caused undefined behavior. – bytecode77 Apr 13 '15 at 19:41
  • That is actually one good application of it. But, that being said, every game written in C++ and C had no problem using plain old arrays. You could always implement a `Board` class that wraps something like a `List`. Personally I would not use the 2D vector at the cost of using LINQ but in this case I could at least understand the decision to do so. – evanmcdonnal Apr 13 '15 at 19:57

1 Answers1

2

Here's a way you can flatten the list to check

bool anyZeroes = array.Cast<int>().Any(value => value == 0);// false
bool anyNines = array.Cast<int>().Any(value => value == 9);// true

Though, if you are making multiple calls you should store it:

bool casted = array.Cast<int>();
bool anyZeroes = casted.Any(value => value == 0);// false
bool anyNines = casted.Any(value => value == 9);// true

Reference: https://stackoverflow.com/a/13822900/526704

Community
  • 1
  • 1
DLeh
  • 23,806
  • 16
  • 84
  • 128
  • Wow, so simple! Why didn't I think of this myself? Thanks :D – bytecode77 Apr 13 '15 at 19:38
  • it's a bit counter-intuitive to me that a multi-dimm array would be able to be so easily "flattened". I had originally thought of it more as a `List>` and tried to do a `SelectMany()` on it, but that doesn't work. I guess `Cast()` just turns it into an `IEnumerable` which LINQ can handle better – DLeh Apr 13 '15 at 19:39