Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# conversion from list<decimal> to double array

This is NET 4.5, so feel free to go crazy with the ideas. =)

I have a very large decimal List, and I need to convert it to an array of doubles. The kicker here is that due to the list size, I want it to be all done in one pass...O(n)

I can do it with two passes, but that makes it O(2n), which is really time intensive and probably unnecessary.

I've been banging my head against this for a couple of hours now, and it's just not clicking. I've used ConvertAll, ToArray, Convert, Lambdas, linq, delegates, you name it. It is seriously not clicking in my head.

Somebody, anybody, show me how its done so I can kick myself and get on with my day. =P

like image 231
The One Rob Avatar asked Dec 26 '22 14:12

The One Rob


1 Answers

What about a simple for loop?

var ary = new double[list.Count];
for (var ii = 0; ii < list.Count; ii++) {
 ary[ii] = Convert.ToDouble(list[ii]);
}

EDIT: I strongly believe that LINQ is the right way to go. It's short, precise and clean.

var ary = list.Select(item => Convert.ToDouble(item)).ToArray();
like image 136
Marko Juvančič Avatar answered Dec 28 '22 05:12

Marko Juvančič