使用OpenFileDialog从CSV文件读取特定的列

时间:2018-08-21 06:53:34

标签: c# winforms linq

我想使用第二和第四列从.csv文件中绘制图形。 数据从第9行开始,我可以跳过8行。但是我想访问用于绘制图形的特定列。

 CSV file to be used for plotting graph with col2 and col4

string ChosenFile = "";

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    ChosenFile = openFileDialog1.FileName;
    char delimited = ',';

    if (new FileInfo(ChosenFile).Length != 0)
    {
        try
        {
            var data = File.ReadLines(@ChosenFile).Skip(8)
               .Select(line => line.Split(new Char[] { delimited }, StringSplitOptions.RemoveEmptyEntries))
               .Select(chunk => chunk
               .Select(x => Double.Parse(x, CultureInfo.InvariantCulture))
               .ToArray());

            series.Points.Clear();
            foreach (var pair in data)
            {
                series.Points.AddXY(pair[0], pair[1]);                          
            }
       }
        catch
        {
            logger.info("The file " + openFileDialog1.FileName + " cannot be opened because the content may be invalid or damaged.");
        }
    }
    else logger.info(openFileDialog1.FileName + " is an empty file.");
}

此LINQ语句仅访问前两列,但对于我的应用程序,我需要访问第二列和第四列的数据 我需要在此语句中进行哪些更改才能获得这些列?

1 个答案:

答案 0 :(得分:0)

首先让我们解决您的问题。数据中的每一列都可以通过索引访问。

char delimited = ',';
var inputCSV = @"Skip it
Skip ita
Skip it
Col1,Col2,Foo,Bar
2.3,0.2,3.0,40.5
2.3,0.2,3.0,40.5
2.3,0.2,3.0,40.5";

var fileReadLinesMimic = inputCSV
                    .Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var data = fileReadLinesMimic
            .Skip(4)
            .Select(line => line.Split(new Char[] { delimited }, StringSplitOptions.RemoveEmptyEntries))
            .Select(chunk =>
                chunk.Select(x => Double.Parse(x, CultureInfo.InvariantCulture)
            )
            .ToArray());

foreach (var item in data)
{
    Console.WriteLine($"Col1={item[0]}; Col2={item[1]}; Foo={item[2]}; Bar={item[3]};");
}