首页 > 解决方案 > C# 仅当列表中存在列名时才从 CSV 文件中读取列

问题描述

我有一个从文件读取到列表中的列标题列表:

// Read column headers from text file
List<string> colHeads = new List<string>();
string[] lines = File.ReadAllLines("C:\\DATA\\MLData\\colHeads.txt");
string[] spl = new string[100];

foreach (string line in lines)
{
    spl = line.Split('=');
    colHeads.Add(spl[0].Trim());
}

然后我想读取一个 CSV 文件,但只读取列表中的列:

// Read CSV file
string[] lines = File.ReadAllLines("C:\\DATA\\MLData\hist.csv");
string[] spl = new string[500];

foreach (string line in lines)
{
        spl = line.Split(',');
        var rec = new Record()
        {
            Name = spl[1],
            ident = float.Parse(spl[4], CultureInfo.InvariantCulture.NumberFormat),
            location = float.Parse(spl[5], CultureInfo.InvariantCulture.NumberFormat),
            ...
            ...
        };
}

colHeads.txt 的示例....

Name
ident
location
...

hist.csv 的示例...

Name,yob,ident,level,location,score1
John B,1981,23,3,GB,54

hist.csv 中的列比 colHeads.txt 多,所以我需要一种按列名而不是列号读取 csv 文件的方法,忽略不在列表中的列。我分配的变量与列名完全匹配。

标签: c#csv

解决方案


假设colHeads包含标题名称列表,您可以尝试这样的事情。

location = colHeads.Contains("location") ? float.Parse(spl[5], CultureInfo.InvariantCulture.NumberFormat) : 0

如果可用列的集合始终相同,并且您只想更改读取的列,那么这对于基本使用可能会很好。


推荐阅读