将文本文件解析为字典C#<string> <int> </int> </string>

时间:2014-11-24 12:55:56

标签: c# asp.net

我有一些代码无法将文本文件解析为字典...

 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,。

4 个答案:

答案 0 :(得分:0)

你的字典被声明为<string, int>,但你要添加的第二个值是另一个字符串(来自sr.ReadLine)我想你想要一个<string, string>字典

答案 1 :(得分: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);
                }
            }
        }

答案 2 :(得分: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; 
}

答案 3 :(得分: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);
            }