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?

8
  • 2
    That's a 2d array not an array of arrays(jagged array). Commented Dec 11, 2012 at 15:16
  • 1
    You're right... it's a multidimensional array. Commented Dec 11, 2012 at 15:19
  • possible duplicate of Convert 2 dimensional array Commented Dec 11, 2012 at 15:20
  • There is a linq query in the duplicate, but i would go with a foreach as the linq query is quite opaque and the foreach is clear what you are doing. Commented Dec 11, 2012 at 15:21
  • 1
    'var flatNumbers = numbers.Cast<int>();' copied and modified from the linked post. All LINQ Commented Dec 11, 2012 at 15:24

3 Answers 3

28

Perhaps simply:

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

Demo

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

2 Comments

+1 from me - Cast is a has a little less overhead then OfType in this case
Upvoted. But in either way we get boxing and unboxing because this goes through the non-generic IEnumerable interface which yields object boxes which are the unboxed by Cast.
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);

Comments

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>();

3 Comments

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.
Please post your whole problem as you will get different answers
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 ;-)

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.