我正在读取一个 StreamReader
的文件.现在我想将内容读入 Dictionary<string, List<string>>
我读取的文件是这样的:
'someKey'
Value1someKey
'anotherKey'
Value1another Value2anotherKey
我正在使用以下代码获取 key
reactionInfo = new Dictionary<string, List<string>>();
string line;
StreamReader reader = new StreamReader(filePath);
while ((line = reader.ReadLine()) != null)
{
if (line.Trim().StartsWith("'"))
{
List<string> values = new List<string>();
if(!reactionInfo.TryGetValue(line,out values))
{
reactionInfo.Add(line, new List<string>());
}
}
}
如何将下一行的值映射到上一行中的键?
最佳答案
读取循环中的下一行以添加这些值,同时将条目添加到字典中。下面几行读取下一行,可以边加边加。
var valuesStrings = reader.ReadLine().Split(' ');
完整代码:
reactionInfo = new Dictionary<string, List<string>>();
string line;
using(StreamReader reader = new StreamReader(filePath))
{
while ((line = reader.ReadLine()) != null)
{
if (line.Trim().StartsWith("'"))
{
List<string> values = new List<string>();
if(!reactionInfo.TryGetValue(line,out values))
{
var valuesStrings = reader.ReadLine().Split(' ');
reactionInfo.Add(line, values.Length > 0 ? new List<string>(new List<string>(valuesStrings)) : new List<string>());
}
}
}
}
附加建议:
将 StreamReader 包装到 using block 中。
关于c# - 如何读取和处理属于一起的多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50407248/