2014-11-24 47 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); 
      }