views:

87

answers:

4

EDIT : I had tried these two ways before -

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

List 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.

+6  A: 

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
That works thanks!!
Misnomer
A: 

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
A: 

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
+2  A: 

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