Reputation: 33
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[]'
Upvotes: 3
Views: 1690
Reputation: 14477
File.ReadLines("decimal list.txt")
.Select(l => Convert.ToDouble(l))
.ToArray();
Upvotes: 3
Reputation: 232
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));
Upvotes: 0
Reputation: 6580
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);
}
}
Upvotes: 0
Reputation: 613202
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.
Upvotes: 1
Reputation: 460208
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();
Upvotes: 1
Reputation: 46
You could loop through the string array and use Double.Parse or Double.TryParse (if you might have strings that won't parse as doubles in the array).
Upvotes: 0
Reputation: 186803
You can use Linq:
Double fi[] = File.ReadLines("list of stopword.txt")
.Select(x => Double.Parse(x, CultureInfo.InvariantCulture))
.ToArray();
Upvotes: 9