[英]Convert array of string to array of double
I have a text file (.txt) with some decimal number : 我有一个带有一些十进制数的文本文件(.txt):
0.3125
0.3
0.181818181818182
0.333333333333333
0.210526315789474
0.181818181818182
and I want to take these number to array of double. 我想把这些数字带到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[]' 不能将'double'类型转换为'double []'
You can use Linq : 你可以使用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. 您收到错误是因为您尝试将double
( Convert.ToDouble
)分配给double[]
变量。 Instead you have to parse every line to double and create an array. 相反,您必须将每一行解析为double并创建一个数组。
You can use LINQ: 您可以使用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
. 唯一匹配的Convert.ToDouble
重载是接收Object
重载。 This function, like all the other ToDouble
overloads, returns double
. 与所有其他ToDouble
重载一样,此函数返回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. 因此,您尝试将double
赋值给double[]
,编译器会告诉您它不能这样做。
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. 当然,如果你曾经将你的string[]
数组传递给Convert.ToDouble
重载,它将因运行时错误而失败,因为Convert.ToDouble
期望接收单个值,并返回单个值。 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. 您需要做的是将文件中的每一行转换为double。 An effective way to do that would be to use a Linq query as demonstrated by various other answers. 一种有效的方法是使用Linq查询,如各种其他答案所示。
你可以循环遍历字符串数组并使用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. 那是因为Convert.ToDouble返回一个双精度值,左侧有double [](双精度变量数组)。
Try instead: 尝试改为:
List<double> list = new List<double>();
foreach(string line in File.ReadLines("list of stopword.txt"))
list.Add(double.Parse(line));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.