我有一些代码无法将文本文件解析为字典...
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,。
发布于 2014-11-24 20:59:40
您的字典声明为<string, int>,但是添加的第二个值是另一个字符串(来自sr.ReadLine),我认为您需要一个<string, string>字典
发布于 2014-11-24 21:01:22
您可能希望如下所示:
你的key是行号,你的字符串是你的行;
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);
}
}
}发布于 2014-11-24 21:17:56
我想这就是你想要做的。
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;
}https://stackoverflow.com/questions/27105375
复制相似问题