如何使用Linq将制表符分隔文件读入多维数组?

时间:2015-09-04 13:35:06

标签: c# linq tab-delimited

对于以下制表符分隔文件,我正在尝试将其保存在double[][] csvArray

cols的数量是final(5),但是行是动态的

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

除了迭代整个矩阵之外,是否有一些LINQ表达式可以获得这个漂亮和干净的效果?

2 个答案:

答案 0 :(得分:3)

Linq 的帮助下,您可以这样做:

SELECT id, title, image, address, serviceType 
FROM `ta` 
ORDER BY CASE WHEN title LIKE '[0-9]%' THEN 1
              WHEN title LIKE '[A-Z]%' THEN 2
              ELSE 3 END
LIMIT 0,20 

请注意,当使用锯齿状数组(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(); )时,您无需知道确切的列数(在您的情况下为5)

答案 1 :(得分:0)

这会起作用。

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