简体   繁体   中英

Convert array of string to array of double

I have a text file (.txt) with some decimal number :

0.3125
0.3
0.181818181818182
0.333333333333333
0.210526315789474
0.181818181818182

and I want to take these number to array of double. Here's my code :

double[] f1 = Convert.ToDouble(File.ReadLines("decimal list.txt").ToArray());

But I get and error of

Cannot implicity convert type 'double' to 'double[]'

You can use Linq :

  Double fi[] = File.ReadLines("list of stopword.txt")
                    .Select(x => Double.Parse(x, CultureInfo.InvariantCulture))
                    .ToArray();
File.ReadLines("decimal list.txt")
    .Select(l => Convert.ToDouble(l))
    .ToArray();

You get the error because you are trying to assign a double ( Convert.ToDouble ) to a double[] variable. Instead you have to parse every line to double and create an array.

You can use LINQ:

double value = 0;
double[] f1 = File.ReadLines("decimal list.txt")
    .Where(l => double.TryParse(l.Trim(), out value))  // skips invalid lines
    .Select(l => value)
    .ToArray();

The only Convert.ToDouble overload that matches is the one that receives Object . This function, like all the other ToDouble overloads, returns double .

public static double ToDouble(
    Object value
)

You are therefore attempting to assign a double to a double[] and the compiler tells you that it cannot do so.

Of course, if you ever did pass your string[] array to that Convert.ToDouble overload it would fail with a runtime error because Convert.ToDouble expects to receive a single value, and return a single value. It simply does not convert multiple values in a single call.

What you need to do is convert each line from the file into a double. An effective way to do that would be to use a Linq query as demonstrated by various other answers.

你可以循环遍历字符串数组并使用Double.Parse或Double.TryParse(如果你的字符串不能解析为数组中的双精度数)。

Something like (not tested):

string[] lines = File.ReadAllLines("decimal list.txt");
List<doulbe> values = new List<double>();

foreach(string line in lines)
{
    double value;

    if (double.TryParse(line, out value))
    {
        values.Add(value);
    }
}

That's because Convert.ToDouble returns a single double-precision value and you have double[] (array of double-precision variables) on the left side.

Try instead:

List<double> list = new List<double>();
foreach(string line in File.ReadLines("list of stopword.txt"))
  list.Add(double.Parse(line));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM