1

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!

3
  • 1
    Ok you said the values variable holds all values from the file (somehow) as array.. err cos you said a.Split(';') .. so now its an array of strings... Commented Apr 4, 2017 at 9:02
  • It's more usefull to use the File.ReadLines instead of the File.ReadAllLines, because the File.ReadLines streams the data instead of loading it full into the memory. Commented Apr 4, 2017 at 9:05
  • 2
    The file contains more than one line? So It would be a double[][] What do you need as result? double[][] or double[] (all lines merged) Commented Apr 4, 2017 at 9:07

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, the .SelectMany statement fixed it!
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.