10

Is there an elegant way to flatten a 2D array in C# (using Linq or not)?

E.g. suppose

var my2dArray = new int[][] {
   new int[] {1,2,3},
   new int[] {4,5,6}
};

I want to call something like

my2dArray.flatten()

which would yield

{1,2,3,4,5,6}

Any ideas?

Cedric Druck
  • 1,032
  • 7
  • 20
  • 3
    Note this is actually a jagged array and not a 2D array. Thus you cannot limit the size of the inner arrays. Your code would not compile unless you remove the 3 in `new int[][3]`. – juharr Sep 15 '15 at 14:04
  • @M.kazemAkhgary you are right, thanks for picking me up on that :) – Jeremy Thompson Sep 15 '15 at 14:41

1 Answers1

30

You can use SelectMany

var flat = my2dArray.SelectMany(a => a).ToArray();

This will work with a jagged array like in your example, but not with a 2D array like

var my2dArray = new [,] { { 1, 2, 3 }, { 1, 2, 3 } };

But in that case you can iterate the values like this

foreach(var item in my2dArray)
    Console.WriteLine(item);
juharr
  • 31,741
  • 4
  • 58
  • 93
  • Yup that does the trick, perfect! I am still a bit confused about the real 2D arrays, they don't seem very convenient to use... – Cedric Druck Sep 15 '15 at 15:07
  • @CedricDruck The difference is that a jagged array's second dimension can vary where as a 2D array has a fixed size for both dimensions. Check out this [question](http://stackoverflow.com/questions/597720/what-are-the-differences-between-a-multidimensional-array-and-an-array-of-arrays) for more details. – juharr Sep 15 '15 at 15:37
  • The linked question confirms ... I'll stick to jagged arrays. I've been using those in multiple other languages anyway. The nicer syntax may be useful in some cases, but one can easily work without it... Thanks for the pointers. – Cedric Druck Sep 15 '15 at 16:11
  • @CedricDruck You might want to just switch to lists like `List>` the advantage is that you can easily add and remove elements, but it depends on what you want to do. – juharr Sep 15 '15 at 16:17
  • 1
    Indeed, in this case the size of the collection is fixed, so no need. But in general I prefer using more flexible structures such as List or Dictionary. – Cedric Druck Sep 15 '15 at 16:23