简体   繁体   English

如何在c#中使用一维字符串类型数组代替双类型二维锯齿数组?

[英]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文件中每一行的数据格式为: 5.1,3.5,1.4,0.2

There are total 150 rows in text file.文本文件共有 150 行。 I want to read file line by line, split by comma and save each line in double type array as in case of rawData[]][] .我想逐行读取文件,用逗号分割,并将每一行保存在双类型数组中,就像rawData[]][]

Try using Linq , you have to尝试使用Linq ,你必须

  1. Read file line by line逐行读取文件
  2. Split each line into items by comma用逗号将每一行拆分为多个items
  3. Convert each item into Double每个项目转换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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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