简体   繁体   中英

How to use 1D string type array in place of double type two dimensional jagged array in c#?

I have data in this form:

double[][] rawData = new double[3][];
rawData[0] = new double[] { 65.0, 220.0 };
rawData[1] = new double[] { 73.0, 160.0 };
rawData[2] = new double[] { 59.0, 110.0 };

Now I want to import data from text file and use in place of this array data. I want double type jagged array for text file data too.

Data of each row in file is of form: 5.1,3.5,1.4,0.2

There are total 150 rows in text file. I want to read file line by line, split by comma and save each line in double type array as in case of rawData[]][] .

Try using Linq , you have to

  1. Read file line by line
  2. Split each line into items by comma
  3. Convert each item into Double
  4. Materialize items into (inner) array
  5. Materialize lines into (outer) array

Implementation

  // let txt file being a CSV-like one
  Double[][] data = File
    .ReadLines(@"C:\MyFile.txt")
    .Where(line => !String.IsNullOrEmpty(line.Trim())) // to remove empty lines if any
    .Select(line => line.Split(','))
    .Select(items => items
      .Select(item => Double.Parse(item, CultureInfo.InvariantCulture))
      .ToArray()) // inner array
    .ToArray();   // outer array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM