迭代List时如何追加几行?

时间:2014-01-08 05:13:29

标签: c# list text-parsing

如果有人可以提供以下建议,我会很感激。

我阅读了包含以下文字的文件,并将每一行写入List<string>

CODE/1
NAME/some_name1
SHORT_NAME/short_name1   
CODE/2
NAME/document is a piece of paper 
containing information often 
used as proof of something
SHORT_NAME/document is a piece 

现在我正在解析列表以分别获取CODE, NAME and SHORT_NAME。 问题是包含NAME的某些行有一个因为长度很长而被分成几行的行。我想将这些行附加到一个句子中,输出应为:

...
NAME/document is a piece of paper containing information often used as proof of something
...

我的代码只附加下一行:

List<string> lines = File.ReadLines(path).ToList();
List<string> full_lines = new List<string>();

foreach (string line in lines)
         {               
            if (line.StartsWith("NAME"))
            {

                name_index = lines.IndexOf(line);
                string new_line = "";
                if (!lines.ElementAt(name_index + 1).StartsWith("SHORT_NAME")) //checking if   
                //the next line does not start with SHORT_NAME (then it is continuation of NAME)
                {                       
                    new_line = line + " " + lines.ElementAt(name_index + 1);//appending the next
                                                                            //line
                    full_lines.Add(new_line); //adding into new list
                }                   
                else
                {                        
                    full_lines.Add(line);
                }
            }
          }

所以输出是:

 ...
NAME/document is a piece of paper
...

那么,我怎样才能附加所有行?

谢谢

2 个答案:

答案 0 :(得分:1)

当您阅读文件时,请分别阅读每一行,而不是一起阅读。然后不要创建新行,除非它以关键字开头或'/'是唯一的,除非该行包含'/'。这样的事情可能会有所帮助:

List<string> full_lines = new List<string>();
System.IO.StreamReader sr = new System.IO.StreamReader(path);
string line = "";
while(!sr.EndOfStream)
{
    line = sr.ReadLine();
    if(!line.Contains("/"))
    {
        full_lines[full_lines.Count - 1] += line;
    }
    else
        full_lines.Add(line);
}

答案 1 :(得分:0)

变化

 if (!lines.ElementAt(name_index + 1).StartsWith("SHORT_NAME")) //checking if   
                //the next line does not start with SHORT_NAME (then it is continuation of NAME)
                {                       
                    new_line = line + " " + lines.ElementAt(name_index + 1);//appending the next
                                                                            //line
                    full_lines.Add(new_line); //adding into new list
                }                   
                else
                {                        
                    full_lines.Add(line);
                }

     new_line = line;
     name_index++;
     while (!lines.ElementAt(name_index).StartsWith("SHORT_NAME"))                       
     {                       
     new_line = new_line + " " + lines.ElementAt(name_index);//appending the next line
     name_index++;
     }  

     full_lines.Add(new_line);