How can I read a tab delimited file in a multidimensional array using Linq?

For the next tab delimited file, I'm trying to save it to double[][] csvArray

The cols number is final (5), but the strings are dynamic

1,717.72    1,728.89    1,712.61    1,728.89    1,707.11
1,701.19    1,704.11    1,702.05    1,706.98    1,697.19
1,685.41    1,688.68    1,694.07    1,695.71    1,687.20
1,641.05    1,649.27    1,658.06    1,658.58    1,648.09
1,673.69    1,668.34    1,663.90    1,673.42    1,662.16
1,682.32    1,669.54    1,671.33    1,681.02    1,668.81
1,688.12    1,681.44    1,684.90    1,688.57    1,672.60
1,686.02    1,690.76    1,697.13    1,698.13    1,690.35
1,704.92    1,696.22    1,696.74    1,701.17    1,688.74
1,686.78    1,683.61    1,677.03    1,687.88    1,674.40
1,705.94    1,704.90    1,715.58    1,716.91    1,700.25
1,659.22    1,660.46    1,658.69    1,664.98    1,655.62
1,622.31    1,621.94    1,632.78    1,633.61    1,613.91

Is there any LINQ expression that can get this beautiful and clean, besides iterating the whole matrix?

+4
source share
2 answers

With Linq, you can do it like this:

using System.Globalization;

var csvArray = File
  .ReadLines(@"C:\MyData.csv") // assuming that data is in the file
  .Select(line => line
    .Split('\t')
    .Select(item => Double.Parse(item, CultureInfo.InvariantCulture))
    .ToArray()) 
  .ToArray();

note that when using jagged arrays ( double[][]) you don't need to know the exact number of columns (5 in your case)

+3
source

This will work.

string str = 
  @"1,717.72    1,728.89    1,712.61    1,728.89    1,707.11    
    1,717.72    1,728.89    1,712.61    1,728.89    1,707.11";

var doubles = str
  .Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
  .Select(item => item
    .Split("\t".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
    .Select(d => double.Parse(d))
    .ToArray())
  .ToArray();
0
source

Source: https://habr.com/ru/post/1605955/


All Articles