Reputation: 13
I have a question concerning LINQ queries and return types. I just want to read values from a .csv file, where there are double values separated by semicolon like this:
0,016;0,010;-0,020;-0,014;0,020;0,016;-0,019;-0,014;0,023;
The reading from the file works fine with the following statement:
double pdValue;
double[] pdValues;
var values = File.ReadAllLines(path)
.Select(a => a.Split(';')
.Select(str => double.TryParse(str, out pdValue) ? pdValue : 0));
pdValues = values.ToArray();
But the last line returns the 'Cannot implicitly convert System.Collections.Generic.IENumerable< double> to double[]' error. Trying to get it to work with array changes the error to 'Cannot implicitly convert System.Collections.Generic.IENumerable< double>[] to double[]'.
When debugging, I can already see that the values variable holds all values from the file (somehow) as array...
I could not find anything yet, what could give me a hint on what exactly I am doing wrong here. Can anybody help me?
Thanks in advance!
Upvotes: 1
Views: 1665
Reputation: 298
The ReadAllLine
method will return an array of strings ( Lets say Array A). The Split
method that you have used is going to give you a string array split by ";" for every item of Array A. So the end result would be an array of array. That is the reason for the error.
You can try :
var values = File.ReadAllLines(path).ToString()
.Split(';').Select(str => double.TryParse(str, out pdValue) ? pdValue : 0);
Upvotes: 1
Reputation: 1301
Look at the values
variable type which is IEnumerable<IEnumerable<double>>
. You should use this code:
var values = File.ReadAllLines(path)
.SelectMany(a => a.Split(';')
.Select(str => double.TryParse(str, out pdValue) ? pdValue : 0));
pdValues = values.ToArray();
Upvotes: 3