将文本文件解析为字典 C#

本文关键字:int string 字典 文本 文件 | 更新日期: 2023-09-27 18:31:47

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

 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());
                }
            }
        }

最后一行是它失败的地方。它不喜欢字典。添加(行,sr.ReadBlock()) 语句。我哪里出错了?

我需要读取一个字符串,后跟一个 int,。

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

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

可能你想这样做:

您的键是行号你的绳子就是你的线;

 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);
                }
            }
        }

我认为这就是您要做的。

使用流阅读器来计算重复项?

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; 
}

如果您尝试将一行添加为键,并将文件中的后续数字添加为值,它应如下所示:

           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);
            }