How to use LINQ on a multidimensional array to 'unwind' the array?

Consider the following array:

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

I would like to use LINQ to construct an IEnumerable with numbers 2, 1, 3, 4, 6, 5.

What would be the best way to do so?

Answers


How about:

Enumerable
    .Range(0,numbers.GetUpperBound(0)+1)
    .SelectMany(x => Enumerable.Range(0,numbers.GetUpperBound(1)+1)
    .Select (y =>numbers[x,y] ));

or to neaten up.

var xLimit=Enumerable.Range(0,numbers.GetUpperBound(0)+1);
var yLimit=Enumerable.Range(0,numbers.GetUpperBound(1)+1);
var result = xLimit.SelectMany(x=> yLimit.Select(y => numbers[x,y]));

EDIT Revised Question....

var result = array.SelectMany(x => x.C);

Perhaps simply:

var all = numbers.Cast<int>();

Demo


Use simple foreach to get your numbers from 2d array:

int[,] numbers = new int[3, 2] { { 2, 1 }, { 3, 4 }, { 6, 5 } };
foreach(int x in numbers)
{
   // 2, 1, 3, 4, 6, 5.
}

LINQ (it's an big overhead to use Linq for your initial task, because instead of simple iterating array, CastIterator (Tim's answer) of OfTypeIterator will be created)

IEnumerable<int> query = numbers.OfType<int>();

Need Your Help

How to escape "<" character in regex in Solr schema.xml?

java regex solr

Using Solr 3.5.0 and in my schema.xml I'm using the following to mark the end of sentences and replace the end punctuation with a symbolic token:

What does Collections.unmodifiableSet() do in Java?

java final unmodifiable

I can see that Collections.unmodifiableSet returns an unmodifiable view of the given set but I don't understand why we can't just use the final modifier to accomplish this.