[英]Parse text file into dictionary C# <string> <int>
I have some code that is not working for parsing a text file to a dictionary... 我有一些无法将文本文件解析为字典的代码...
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());
}
}
}
The last line is where it fails. 最后一行是失败的地方。 It does not like the dictionay.Add(Line, sr.ReadBlock()) statements.
它不喜欢dictionay.Add(Line,sr.ReadBlock())语句。 Where am I going wrong?
我要去哪里错了?
I need to read in a string followed by an int,. 我需要读入一个字符串,后跟一个int。
您的字典被声明为<string, int>
但是您要添加的第二个值是另一个字符串(来自sr.ReadLine)我认为您想要的是<string, string>
的字典
Probably you want to make it as follows: 可能您希望使其如下所示:
Where your key is line number and your string is your line; 您的密钥是行号,字符串是行;
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);
}
}
}
I think this is what you're trying to do. 我认为这就是您想要做的。
Using StreamReader to count duplicates? 使用StreamReader计数重复项?
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;
}
If you are trying to add a line as a key and subsequent number from file as a value, it should look like this: 如果您尝试添加一行作为键,并将文件中的后续数字添加为值,则应如下所示:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.