Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 589
  • Last Modified:

How to cast an ArrayList to a double[] array?

double[] costArray;
...
costArray = callToDoSomething(paramaters...);
---------------------------

As you can see the costArray is a double array, and the "callToDoSomething" method returns an ArrayList.

I need costArray to be of type double[] but in the 'callToDoSomething' method I have to return an arraylist because the contents are dynamically added.

Any suggestions on casting/converting to an array from the arraylist?
0
djs120
Asked:
djs120
  • 3
  • 2
  • 2
1 Solution
 
BurntSkyCommented:
ArrayList costArray = callToDoSomething(...);

double[] costArray2 = new double[costArray.Length];
costArray.CopyTo(costArray2);
0
 
djs120Author Commented:
I noticed there is a .ToArray() method for ArrayLists, would this be helpful to me at all?  
0
 
djs120Author Commented:
And where you say to do:

double[] costArray2 = new double[costArray.Length];

I can't get the .Length property on the ArrayList.  Suggestions?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Diego PazosCommented:
To get the number of objects in an ArrayList you have to query the 'Count' property.
Anyway, AFAIK, the CopyTo method only works with an Array class as destination, and not with a 'pure' array.
So I guess you're stuck with using something like:

ArrayList AL = new ArrayList();
//Populate ArrayList            
double[] A = new double[AL.Count];
for (int I=0; I <= AL.Count - 1; I++) {
    A[I] = Convert.ToDouble(AL[I]);
}
0
 
BurntSkyCommented:
Oops, uKER is correct; use ArrayList.Count.

And a "pure" array is derived from the Array class, so yes, it will work with the CopyTo() method.
0
 
djs120Author Commented:
Thanks guys.
0
 
Diego PazosCommented:
BurntSky is right, I checked and it does work. Only check you explicitly add the objects as integers.
The following code won't work, as there is no explicit conversion when copying the elements to the array:

ArrayList AL = new ArrayList();
AL.AddRange(new object[] { 1, 2, 3 });
double[] A = new double[AL.Count];
AL.CopyTo(A);

This is because 1, 2 and 3 are integer values and implicitly assigning them to the array's double values generates an exception.
This particular case could be fixed by specifying the array as {1.0, 2.0, 3.0}
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now