1

I have a class that encapsulates an array like this :

public class Data
{
    public double[] buffer  = new double[10];
}

Then I have an array of Data objects:

Data[] arrayOfData  = new Data[10];

What is the most efficient way to get a jagged array double[][] from all the buffer in all arrayOfData objects ?

fubo
  • 44,811
  • 17
  • 103
  • 137
Heefoo
  • 125
  • 1
  • 8
  • 3
    In terms of which efficiency? Performance? Memory? Ease of writing the code? – Uwe Keim Sep 07 '15 at 14:54
  • 2
    Define efficient: easy to write? Easy to read? Fast to run? If the last one: how fast? What are you bottlenecking on? – Martijn Sep 07 '15 at 14:54

2 Answers2

0

Linq would be one option

double[][] result = arrayOfData.Where(x => x != null).Select(x => x.buffer).ToArray();

UPDATE: added a null-check because Data can be null but double not

fubo
  • 44,811
  • 17
  • 103
  • 137
  • 2
    Isn't [`SelectMany`](http://stackoverflow.com/questions/958949/difference-between-select-and-selectmany) available to not have multiple `Select` calls? – Uwe Keim Sep 07 '15 at 14:56
  • 2
    @UweKeim I think that would only help if you were going for a `double[]` rather than a `double[][]`. But the nested `Select` does look unnecessary, since there's no change being done. – 31eee384 Sep 07 '15 at 15:07
0

You can simply use for loop here. It's just two lines of code :

Data[] arrayOfData  = new Data[10];
double[][] allBuffers = new double[arrayOfData.Length][];

for(int i = 0; i < arrayOfData.Length; i++) allBuffers[i] = arrayOfData[i].buffer;

Or if you prefer to do it with LINQ:

double[][] allBuffers = arrayOfData.Select(a => a.buffer).ToArray();

The problem with this line of code however is that LINQ has set of extension methods for interface IEnumerable<T> and therefore it uses foreach loop that is considerably slower than for and is widely used only to iterate through collections and not arrays.

Fabjan
  • 13,506
  • 4
  • 25
  • 52
  • the linq part is c&p from my answer -1 – fubo Sep 10 '15 at 06:00
  • @fubo no fubo, it isn't. You've used two `.Select()` methods in your answer and only later you've edited your answer... But this doesn't matter because this question is not accurate anyway... – Fabjan Sep 10 '15 at 06:28