使用标头指定CSV中的列
本文关键字:CSV | 更新日期: 2023-09-27 18:25:54
是否可以编写一个函数,使用CSV中的标题来指定要使用的列?
例如,我有一个CSV格式:
Name,LastName,Age,Address
Bob,Green,26,123 This Street
Jane,Doe,35,234 That Street
我有另一种格式:
LastName,Name,Address,Age
Brown,Dave,123 Other Street,17
Jane,Doe,234 That Other Street,35
我想要Name
、LastName
和Address
,我可以/如何使用标题来指定列?
您可以从第一行获得标题的索引,即
int indexOfName = firstLineOfCSV.Split(',').ToList().IndexOf("Name");
然后,当你逐行读取csv时,寻找第n个值来获得名称的值,即
string name = csvLine.Split(',')[indexOfName];
您可能还想首先将其加载到数据表中,如图所示。然后您可以过滤您需要的内容。
可以编写一个小类来帮助您将列名映射到索引(这是未经测试的,但应该非常接近)
class Csv
{
// Maps the column names to indices
Dictionary<String, int> columns = new Dictionary<String, int>();
// Store rows as arrays of fields
List<String[]> rows = new List<String[]>()
public Csv(String[] lines)
{
String[] headerRow = lines[0].Split(',');
for (int x = 0; x < headerRow.Length; x += 1)
{
// Iterate through first row to get the column names an map to the indices
String columnName = headerRow[x];
columns[columnName] = x;
}
for (int x = 1; x < lines.Length - 1; x += 1)
{
// Iterate through rows splitting them into each field and storing in 'rows' variable
rows.Add(lines[x].Split(','); // Not properly escaping (e.g. address could have "Memphis, Tn")
}
}
// Method to get a field by row index and column name
public Get(int rowIndex, String columnName)
{
int columnIndex = columns[columnName];
return rows[rowIndex][columnIndex];
}
}