12

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?

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203

3 Answers3

28

Perhaps simply:

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

Demo

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
7

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);
mihai
  • 4,592
  • 3
  • 29
  • 42
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
6

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>();
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • I need to use LINQ. My problem is a tat more complex... but I need to use LINQ. Each object in the array has a property that has an array that I'll need to mash into a single list. – Kees C. Bakker Dec 11 '12 at 15:21
  • 1
    Please post your whole problem as you will get different answers – Ben Robinson Dec 11 '12 at 15:21
  • 2
    It may be homework, but it may also be the smallest working example of a mind-bogglingly complex system, which the asker didn't want to bother us with ;-) – Tempestas Ludi Dec 18 '17 at 22:53