-2

I want to convert a List<float[]> to List<double[]>

List<float[]> f=new List<float[]>();
List<double[]> d=new List<double[]>();

// ...add float arrays to f...

d.AddRange((doulbe[])f); // Cannot convert type float[] to double[]

is there a way to cast this? so that it won't require a for loop, because I have many lists to be converted.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Mario
  • 13,941
  • 20
  • 54
  • 110
  • The AddRange is implemented as a for loop. You need to do the same (using a for loop, a linq query or anything that enumerate your collection). You can't do it in place – saad Mar 09 '21 at 10:19
  • `Array.ConvertAll`, which is using a loop under the hood – Pavel Anikhouski Mar 09 '21 at 10:20
  • Remember that a `float` and a `double` are different sizes. You can't just take the bits from a `float` and re-interpret them as a `double`. This is what you're asking the cast to do however. – canton7 Mar 09 '21 at 10:20
  • 1
    [C# Cast Entire Array?](https://stackoverflow.com/questions/2068120/c-sharp-cast-entire-array) – Pavel Anikhouski Mar 09 '21 at 10:21
  • @DmitryBychenko Saldly this does not work, you get a InvalidCastException, but it was my first thought as well – Irwene Mar 09 '21 at 10:21
  • Yeah, remember that you can't use generics to invoke user-defined conversion operators – canton7 Mar 09 '21 at 10:22
  • @canton7 I am converting from a lower precision to a higher precision, so it does not lose anything from the numbers. – Mario Mar 09 '21 at 10:45
  • Right, but my point was that an array cast (strictly, a reference conversion) is a different way of looking at the same underlying bits in memory. You can't take the underlying bits of a float and look at them as if they were a double, so an array cast is not going to work. – canton7 Mar 09 '21 at 10:49

1 Answers1

3

You can use:

d.AddRange(f.Select(flArray => Array.ConvertAll(flArray, f => (double)f)));

or:

f.ForEach(flArray => d.Add(Array.ConvertAll(flArray, f => (double)f)));   
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939