2014-10-07 25 views
0

是否可以編寫使用CSV中標題指定要使用哪個列的函數?使用標題指定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 

而我想的NameLastNameAddress,可我/我將如何使用標題來指定列?

回答

1

你可以從第一行標題的指數,即

int indexOfName = firstLineOfCSV.Split(',').ToList().IndexOf("Name"); 

那麼當你讀通過線看第n值的CSV一線得到這個名字的價值,即

string name = csvLine.Split(',')[indexOfName]; 
+0

+1,都採用了類似的方法嘍。 – 2014-10-07 02:36:25

0

您可能還想首先將其加載到數據表中,如here所示。然後你可以過濾你需要的。

0

可以寫一個小的類來幫助你將映射列名的索引(這是未經測試,但應該是相當接近)

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]; 
    } 
} 
相關問題