在C#中的.csv文件中获取特定的行和列值 [英] Getting specific row and column value in .csv file in c#

查看:63
本文介绍了在C#中的.csv文件中获取特定的行和列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.csv文件,如下所示:

I have a .csv file that looks like this:

Index,Time,value
1,0,20
2,1,30

我想做的是在C#中打开.csv文件,然后通过获取 row = 0,column = 0 进行读取,这将为我提供值 1 在上述情况下.很像这样:

What I want to do is to open the .csv file in C# and then read it by getting row = 0, column = 0 which would give me value 1 in the case above. Much like this:

public double GetVal(int row, int column)
{
 ...
 return val;
}

我一直在寻找解决方案,例如以下解决方案:

I have looked around for a solution, for example this one: Remove values from rows under specific columns in csv file

但是我需要能够在函数中同时指定列和行以获取特定值.

But I need to be able to specify both the column and row in the function to get the specific value.

推荐答案

如果CSV文件很简单(没有引号),则可以尝试 Linq :

In case CSV file is simple one (no quotations), you can try Linq:

using System.IO;
using System.Linq;

...

public double GetVal(int row, int column) {
  return File
    .ReadLines(@"c:\MyFile.csv") //TODO: put the right name here
    .Where(line => !string.IsNullOrWhiteSpace(line)) // to be on the safe side
    .Skip(1)   // Skip line with Titles
    .Skip(row)
    .Select(line => double.Parse(line.Split(',')[column]))
    .First();
}

请注意,这段代码会重新读取文件;您可能想一次读取文件 :

Note, that this code re-reads the file; you may want to read the file once:

  string[][] m_Data = File
    .ReadLines(@"c:\MyFile.csv")
    .Where(line => !string.IsNullOrWhiteSpace(line)) 
    .Skip(1)
    .Select(line => line.Split(','))
    .ToArray();

  ...

  public double GetVal(int row, int column) => double.Parse(m_Data[row][col]);

这篇关于在C#中的.csv文件中获取特定的行和列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆