Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list of strings to doubles?

EDIT : I had tried these two ways before -

List<double> doubleList =
stringList.ConvertAll(x => (double)x);

List<double> doubleList =
stringList.Select(x =>
(double)x).ToList();

and got this error:

Cannot convert type 'string' to'double'

I read about something similiar that convert ints to doubles...but I have List of strings which I need to convert to List of doubles and the ConvertAll() does not work neither the Select extension method. Can anyone please help me out.

like image 272
Vishal Avatar asked Jul 29 '10 17:07

Vishal


1 Answers

The select method ought to work if you are using .NET 3.5 or newer:

List<double> result = l.Select(x => double.Parse(x)).ToList();

Here is some example code:

List<string> l = new List<string> { (0.1).ToString(), (1.5).ToString() };
List<double> result = l.Select(x => double.Parse(x)).ToList();
foreach (double x in result)
{
    Console.WriteLine(x);
}

Result:

0,1
1,5

One thing to be aware of is which culture you are using to parse the strings. You might want to use the Parse overload that takes a culture and use CultureInfo.InvariantCulture for example.

like image 107
Mark Byers Avatar answered Oct 15 '22 15:10

Mark Byers