Search code examples
c#arrayslinqparallel-processingplinq

How to read a 2d text file into an 2d array with PLinq


I have a .txt file like this:

1,2,3,4,5  
6,7,8,9,10  
11,12,13,14,15  
16,17,18,19,20

I want to read this file to an double array with PLinq with this code:

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "Text Files(*.txt)|*.txt";
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            number_of_users = File.ReadAllLines(ofd.FileName).Length;
            number_of_services = File.ReadAllLines(ofd.FileName)[0].Split(',').Length;    
            quality_of_service_array = new double[number_of_users, number_of_services]; 
            quality_of_service_array = File.ReadAllLines(ofd.FileName)
               .Select(l => l.Split(',').Select(i => double.Parse(i)).ToArray())
               .ToArray();
}

This array should have 4 rows and 5 columns.
But I get this error:

Cannot implicitly convert type 'double[][]' to 'double[,].

I know the meaning of this error but I'm not expert in PLinq.


Solution

  • You are not using PLINQ. Also, there isn't an easy way of returning a 2d-array from a LINQ query. If you insist on LINQ you could use this method to convert it:

    public T[,] JaggedToMultidimensional<T>(T[][] jaggedArray)
    {
        int rows = jaggedArray.Length;
        int cols = jaggedArray.Max(subArray => subArray.Length);
        T[,] array = new T[rows, cols];
        for(int i = 0; i < rows; i++)
        {
            for(int j = 0; j < cols; j++)
            {
                array[i, j] = jaggedArray[i][j];
            }
        }
        return array;
    }
    

    Then it's simple (used AsParallel because you've mentioned PLINQ):

    double[][] quality_of_service_array = File.ReadLines(ofd.FileName).AsParallel()
        .Select(l => Array.ConvertAll(l.Split(','), double.Parse))
        .ToArray();
    double[,] qos_2d = JaggedToMultidimensional(quality_of_service_array);
    

    This presumes that the format in the text-file is always correct, otherwise you're getting an exception at double.Parse. You could use double.TryParse to check it.