c# - 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 文件的方法,忽略不在列表中的列。我分配的变量与列名完全匹配。
解决方案
假设colHeads
包含标题名称列表,您可以尝试这样的事情。
location = colHeads.Contains("location") ? float.Parse(spl[5], CultureInfo.InvariantCulture.NumberFormat) : 0
如果可用列的集合始终相同,并且您只想更改读取的列,那么这对于基本使用可能会很好。
推荐阅读
- wordpress - 以编程方式创建 woocommerce 产品属性并向其添加术语,但术语未显示在产品->属性中
- excel - Infragistics 网格到 excel 问题
- reactjs - React Hook "useState" 在函数 "AAA" 中被调用,它既不是 React 函数组件也不是自定义 React Hook 函数
- php - 如何在 laravel 中将此代码用于 ntlm sso?
- python-3.x - 无法导入命名元组
- angular - 图像未添加到 Angular 自定义库构建中
- npm - 在 GitHub Pages 中发布网站会导致黑屏。NPM 是问题吗?
- javascript - 跳过与嵌入元素相邻的特定模板标签的模板数组
- python - 将单列中的嵌套字典打开到熊猫中的多列
- amazon-web-services - 仅从我的应用程序访问私有 S3 内容