如何读取和处理属于一起的多行?

How to read and handle multiple lines which belong together?

我正在读取带有 StreamReader 的文件。现在我想将内容读入 Dictionary<string, List<string>>

我读的文件是这样的:

'someKey'
Value1someKey
'anotherKey'
Value1another Value2anotherKey

我正在使用以下代码获取密钥

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 块中。

保留上次读取密钥的副本,然后使用它在下一行中添加值。

reactionInfo = new Dictionary<string, List<string>>();
string line;
using (var reader = new StreamReader(filePath))
{
    var lastKey= "";
    while ((line = reader.ReadLine()) != null)
    {
       if (line.Trim().StartsWith("'"))
       {

            if(!reactionInfo.ContainsKey(line))
            {
              reactionInfo.Add(line, new List<string>());
              lastKey = line;
            }

        }else
            {
              reactionInfo[lastKey].AddRange(line.Split(' ').ToList());
            }
     }
}