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

时间:2018-05-18 08:44:28

标签: c# dictionary streamreader

我正在阅读一个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>());
        }
    }
 }

如何将下一行的值映射到上面一行中的键?

2 个答案:

答案 0 :(得分:1)

读取循环中的下一行,在向词典中添加条目时添加这些值。下面的行读取下一行,可以在添加时添加。

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包装成使用块。

答案 1 :(得分:0)

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

$query = $db->query("SELECT * FROM village ORDER BY name ASC");

    $rowCount = $query->num_rows;

    if($rowCount > 0){
        while($row = $query->fetch_assoc()){
            echo 'Village ID : '.$row['id_kel'].', Village Name : '.$row['nama'].'';
        }
    }else{
        echo "Village name not avaliable'";
    }