2014-11-24 46 views
0

我有一些代碼,不用於解析文本文件到詞典的工作...解析文本文件導入詞典C#<string><int>

Dictionary<string, int> dictDSDRecordsByValidCompCode = new Dictionary<string, int>(); // This dictionary will get rid of pipe delimited comp codes, get distinct, and keep cuont of how many DSD records per Comp Code 

     if (LineToStartOn.pInt > 0) 
     { 
      using (var sr = new StreamReader("\\rvafiler1\rdc\clients\sams\pif\DSD_Dictionary.txt")) 
      { 
       string line = null; 
       string key = null; 
       int value = 0; 

       // while it reads a key 
       while ((line = sr.ReadLine()) != null) 
       { 
        // add the key and whatever it 
        // can read next as the value 
        dictDSDRecordsByValidCompCode.Add(key, sr.ReadBlock); 
        dictDSDRecordsByValidCompCode.Add(value, sr.ReadBlock()); 
       } 
      } 
     } 

最後一行是它失敗。它不喜歡dictionay.Add(Line,sr.ReadBlock())語句。我哪裏錯了?

我需要讀取一個字符串後跟一個int ,.

+0

,因爲你必須定義詞典中和sr.ReadLine()返回字符串,而不是int – codebased 2014-11-24 12:59:08

+0

爲了澄清,你是否想要統計文件中同一行的出現次數? – 2014-11-24 13:12:38

回答

0

你的字典聲明爲<string, int>但要添加的第二個值是另一個字符串(從sr.ReadLine)我想你想的<string, string>

0

字典也許你想它,如下所示:

如果您的鑰匙是行號 而您的字符串是您的行;

var dictDSDRecordsByValidCompCode = new Dictionary<int, string>(); // This dictionary will get rid of pipe delimited comp codes, get distinct, and keep cuont of how many DSD records per Comp Code 

     if (LineToStartOn.pInt > 0) 
     { 
      using (var sr = new StreamReader("\\rvafiler1\rdc\clients\sams\pif\DSD_Dictionary.txt")) 
      { 
       string line = null; 
       int lineNumber = 1; 

       // while it reads a key 
       while (!string.IsNullOrEmpty(line = sr.ReadLine())) 
       { 
        // add the key and whatever it 
        // can read next as the value 
        dictDSDRecordsByValidCompCode.Add(lineNumber++, line); 
       } 
      } 
     } 
+0

我實際上需要讀取一個字符串/ int組合。該字符串表示一個代碼,int表示我讀取該代碼的次數。這是在我的代碼中進一步添加到字典。 – RAW 2014-11-24 13:06:29

0

我想這就是你想要做的。

Using StreamReader to count duplicates?

Dictionary<string, int> firstNames = new Dictionary<string, int>(); 

foreach (string name in YourListWithNames) 
{ 
    if (!firstNames.ContainsKey(name)) 
     firstNames.Add(name, 1); 
    else 
     firstNames[name] += 1; 
} 
0

如果你正試圖從文件中添加一行作爲密鑰,並且隨後的數作爲一種價值,它應該是這樣的:

  string key = null; 
      int value = 0; 

      // while it reads a key 
      while ((key = sr.ReadLine()) != null) 
      { 
       //read subsequent value 
       value = Convert.ToInt32(sr.ReadLine()); 
       //put a key/value pair to dictionary 
       dictDSDRecordsByValidCompCode.Add(key, value); 
      }