将行存储到List中

时间:2011-09-14 16:19:20

标签: c# string list

我有一个文件,我带入RTB。

让我们说它看起来像这样:

// Some Title
// Some Author
// Created on
// Created by
//

Format:
 "Text Length" : 500 lines
 "Page Length" : 20 pages

Component: 123456
 "Name" : Little Red Riding Hood
 "Body Length" : 13515 lines
 ........etc // can have any number of lines under 'Component: 123456'

Component: abcd
 "Name" : Some other Text
 "Body Length" : 12 lines
 ........etc // can have any number of lines under 'Component: abcd'



... etc, etc  // This can occur thousands of times as this file has an unset length.

现在我要做的是存储来自 Component: 123456 的所有内容,直到它到达下一个Component (恰好是abcd并将所有内容存储到List<string>位置0.下一个将位于位置1 ..依此类推,直到读取整个文件。

有谁知道怎么做? - 我不一定需要使用List<string>

1 个答案:

答案 0 :(得分:3)

嗯,你可以这样做:

// I'm assuming you're using .NET 4
var lines = File.ReadLines(filename);

var components = new List<string>();
StringBuilder builder = new StringBuilder();
foreach (var line in lines)
{
    if (line.StartsWith("Component: "))
    {
        components.Add(builder.ToString());
        builder = new StringBuilder();
    }        
    builder.Append(line);
    builder.Append("\r\n");
}

// Get the trailing component
components.Add(builder.ToString());

// Get rid of the first non-component part
components.RemoveAt(0);

(忽略第一个组件之前的位更有效,但它会使代码更复杂。)