8

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.

Community
  • 1
  • 1
Vishal
  • 12,133
  • 17
  • 82
  • 128
  • 1
    "the ConvertAll() does not work neither the Select extension method" - what's wrong? Compiler error? Exception? Something else? Can you provide code? – Tim Robinson Jul 29 '10 at 17:49
  • I was getting Error- Cannot convert type 'string' to 'double' but Mark's answer works!! – Vishal Jul 29 '10 at 17:51
  • You can't **Cast** a string to double (Strings don't implement **explicit conversion to double** --> http://msdn.microsoft.com/en-us/library/xhbhezf4%28v=VS.80%29.aspx). You can only **Parse** it to double as shown in the following answers. – digEmAll Jul 29 '10 at 18:07

5 Answers5

23

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
4

You can use linq:

List<double> myList = myStringlist.ConvertAll(item => double.Parse(item));

Please be aware that parsing doubles and float is complicated - just think of this:

100,00 100.00

-> Different locale settings

Andreas Rehm
  • 2,222
  • 17
  • 20
1

You could use the ForEach method of the List

List<double> dbl= new List<double>;
stringList.ForEach( str=> dbl.Add( double.parse( str ) ) );
Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
0

How about this?

List<string> list = [your strings]
List<double> newList = new List<double>();
for(int i = 0; i < list.Count; i++)
{
  double d = 0;
  if(!double.TryParse(list[i], d)) //Error
  newList.Add(d);
}
AllenG
  • 8,112
  • 29
  • 40
0

Hope this may work: List tmpDouble = tmpString.Select(x => (double ?)Convert.ToDouble (x)).ToList();