Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将行存储到列表中_C#_String_List - Fatal编程技术网

C# 将行存储到列表中

C# 将行存储到列表中,c#,string,list,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 ha

我有一个文件要带到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.
现在我要做的是存储从组件123456到下一个组件(恰好是abcd)的所有内容,并将所有内容存储到列表位置0。下一个将位于位置1。。依此类推,直到读取整个文件


有人知道怎么做吗我不一定需要使用List,您可以执行以下操作:

// 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);

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

你的问题太宽泛了。我觉得你想让我们帮你做家庭作业。你应该写一个能做你想做的事情的应用程序。如果您希望我们根据您的要求向您提供应用程序,那么您就错了。如果您有特定的编程问题,请提问。@Serge:如果您愿意,我可以为您指定。这不是家庭作业,我不在学校。@Abe:我具体的编程问题是:如何存储关键字的值,在本例中是组件,以及其间的所有行,直到它到达以组件开头的下一行。你不应该基于假设对问题进行否决。首先要求澄清。如果生成器!=null,以便builder.Appendline;和builder.AppendEnvironment.NewLine;在里面吗?@theNoobGuy:哇,是的。修正。@theNoobGuy:修正后只删除第一个元素,这简化了事情。效果很好。。但我有一个问题。如果我想使用此代码并拆分以Component开头的行:by var lineSplit=line.split':';因此,我在lineSplit[1]中获取组件的字符串。现在,我尝试使用otherList{if item.PartNumber.ToUpper.EqualslineSplit[1]{//help here?}中的foreach var item将此值与其他列表进行比较。因此,我只想在字符串与不同列表中的另一个字符串匹配时添加每个组件的行。“有没有办法改变你写的内容?”theNoobGuy:对不起,我没有真正理解你的要求。我建议你仔细地问一个新问题,并举例说明。