2013-03-28 66 views
0

我想從這個文件(indexes.csv)得到的信息:正從一個CSV文件中的數據轉換成字典

enter image description here

進入這個類的一個實例:

class Table 
{ 
    Dictionary<String, double> _regionTimeValues; 
    String _region; 

    public Table(String region) 
    { 
     _regionTimeValues = new Dictionary<string, double>(); 
     _region = region; 
     suckInValues(); 
    } 

    private void suckInValues() 
    { 
     //Go find File, get the appropriate Values for _region 
     //add each value found in the csv file that applies, indexed by yearQuarter 
     //Example: _regionTimeValues.Add("2013Q1", 1.1); 
    } 

    internal double locateRelevantValue(string yearQuarter) 
    { 
     double locatedValue = 0.0; 
     _regionTimeValues.TryGetValue(yearQuarter,out locatedValue); 
     return locatedValue; 
    } 

我想只填寫特定地區的數據字典。

如何從csv文件執行此操作?

編輯

區域的一個例子是像「道爾頓」

+0

什麼'region'的例子嗎? –

+0

使用[this](http://stackoverflow.com/questions/5282999/c-net-reading-csv-file)作爲起點,並在其基礎上進行構建。 – shahkalpesh

回答

0

首先一個字符串值,你會讀頭,並得到包含您所在地區的列的索引。然後你將不得不閱讀每行,並用','分隔行,然後閱讀索引來獲得你的價值。您也可以通過搜索分割記錄的第一個索引來應用yr \ qrt。

2

我想你想這樣的事情...

public class Table 
{ 
    private Dictionary<string, double> _regionTimeValues = new Dictionary<string, double>(); 
    private String _region; 

    public Table(String region) 
    { 
     _region = region; 
    } 

    public void AddValue(string key, double value) 
    { 
     _regionTimeValues.Add(key, value); 
    } 
} 

public class Program 
{ 
    static void Main(string[] args) 
    { 
     Dictionary<string, Table> tables = new Dictionary<string, Table>(); 

     using (var reader = new StreamReader("Data.csv")) 
     { 
      // First line contains column names. 
      var columnNames = reader.ReadLine().Split(','); 
      for(int i = 1; i < columnNames.Length; ++i) 
      { 
       var columnName = columnNames[i]; 
       tables.Add(columnName, new Table(columnName)); 
      } 

      var line = reader.ReadLine(); 
      while (line != null) 
      { 
       var columns = line.Split(','); 

       for (int i = 1; i < columns.Length; ++i) 
       { 
        var table = tables[columnNames[i]]; 
        table.AddValue(columns[0], double.Parse(columns[i])); 
       } 

       line = reader.ReadLine(); 
      } 
     } 
    } 
} 
+0

csv文件需要與可執行文件相關的地方在哪裏? – jth41