首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将文本文件解析为字典C# <string> <int>

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

Stack Overflow用户
提问于 2014-11-24 20:55:56
回答 4查看 1.1K关注 0票数 0

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

代码语言:javascript
复制
 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,。

EN

回答 4

Stack Overflow用户

发布于 2014-11-24 20:59:40

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

票数 0
EN

Stack Overflow用户

发布于 2014-11-24 21:01:22

您可能希望如下所示:

你的key是行号,你的字符串是你的行;

代码语言:javascript
复制
 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
EN

Stack Overflow用户

发布于 2014-11-24 21:17:56

我想这就是你想要做的。

Using StreamReader to count duplicates?

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27105375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档