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

标签 c# dictionary streamreader

我正在读取一个 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/

相关文章:

asp.net-mvc-2 - ASP.NET MVC : Can an MSI file be returned via a FileContentResult without breaking the install package?

c# - 使用 C# 在 ASP.Net 中处理大量文件时出现 ERR_EMPTY_RESPONSE

c# - EntityType 没有定义键

c# - 如何在 Xamarin Forms 中使用粗字体?

python - 如何在 PYTHON 中的列表字典中迭代值

python迭代类似dict的对象

c# - 以非升序从大文件中读取多行

C# Pop3 DeleteMessage 不删除电子邮件

c# - 如何从 ELMAH 中排除 404

javascript - ES6 map : Why/When to use an object or a function as a key?