Mark
Mark

Reputation: 108537

Convert List<double[]> to double[,]

Say I have a

List<double[]> x = new List<double[]>();
double[] item = new double[] {1.0,2.0,3.0};
x.add(item);
etc...

Is there a faster/cleaner way to get this into a double[,] then looping it:

double[,] arr = new double[x.Count,3];          
for (row = 0; row < x.Count; row++)
{
    for (col = 0; col < 3; col++)
        arr[row,col] = x[row][col];
}

Thanks.

Upvotes: 2

Views: 1096

Answers (3)

Ekampp
Ekampp

Reputation: 755

There is always the var_export function?

Upvotes: 0

Aren
Aren

Reputation: 55946

Because I felt like it, I solved this using LINQ, however, it's hardly any cleaner. In fact, I'd argue it's less clear, but it'd danm neat :)

// Input
List<double[]> a = new List<double[]>() { 
    new double[]{ 1.0, 2.0, 3.0 },
    new double[]{ 4.0, 5.0, 6.0 },
    new double[]{ 7.0, 8.0, 9.0 }
};

// Output
var b = a.Select((item, index) => new 
            { 
                Items = item.Select((inner, inIndex) => new { Inner = inner, Y = inIndex }),
                X = index 
            })
            .SelectMany(item => item.Items, (i, inner) => new { Value = inner.Inner, X = i.X, Y = inner.Y })
            .Aggregate(new double[a.Count, a.Max(aa => aa.Length)], (acc, item) => { acc[item.X, item.Y] = item.Value; return acc; })

Note: This also works for arbitrarily sized inner double[] arrays, but there will be empty spots.

So yes, there's another way of doing it, but it's not a better way :)

Upvotes: 2

SLaks
SLaks

Reputation: 887459

No, there isn't.

Multi-dimensional arrays are strange beasts and are not widely accepted or used in the BCL.

They're also slow and should be avoided where possible.

Upvotes: 3

Related Questions