字符串生成器与列表

我正在阅读包含数百万行的多个文件,并且我正在创建具有特定问题的所有行号的列表。 例如,如果特定字段留空或包含无效值。

所以我的问题是跟踪可能超过一百万行的数字列表最有效的日期类型。 使用String Builder,Lists或其他更有效的方法吗?

我的最终目标是输出一条消息,如“特定字段在1-32,40,45,47,49-51等处是空白的。所以在String Builder的情况下,我会检查以前的值,如果它是只有一个我会改变它从1到1-2如果它是多于一个将它用逗号分隔。使用List,我只是将每个数字添加到列表然后组合然后文件有已完全阅读。但在这种情况下,我可以有多个包含数百万个数字的列表。

这是我用于使用String Builder组合数字列表的当前代码:

string currentLine = sbCurrentLineNumbers.ToString(); string currentLineSub; StringBuilder subCurrentLine = new StringBuilder(); StringBuilder subCurrentLineSub = new StringBuilder(); int indexLastSpace = currentLine.LastIndexOf(' '); int indexLastDash = currentLine.LastIndexOf('-'); int currentStringInt = 0; if (sbCurrentLineNumbers.Length == 0) { sbCurrentLineNumbers.Append(lineCount); } else if (indexLastSpace == -1 && indexLastDash == -1) { currentStringInt = Convert.ToInt32(currentLine); if (currentStringInt == lineCount - 1) sbCurrentLineNumbers.Append("-" + lineCount); else { sbCurrentLineNumbers.Append(", " + lineCount); commaCounter++; } } else if (indexLastSpace > indexLastDash) { currentLineSub = currentLine.Substring(indexLastSpace); currentStringInt = Convert.ToInt32(currentLineSub); if (currentStringInt == lineCount - 1) sbCurrentLineNumbers.Append("-" + lineCount); else { sbCurrentLineNumbers.Append(", " + lineCount); commaCounter++; } } else if (indexLastSpace < indexLastDash) { currentLineSub = currentLine.Substring(indexLastDash + 1); currentStringInt = Convert.ToInt32(currentLineSub); string charOld = currentLineSub; string charNew = lineCount.ToString(); if (currentStringInt == lineCount - 1) sbCurrentLineNumbers.Replace(charOld, charNew); else { sbCurrentLineNumbers.Append(", " + lineCount); commaCounter++; } } 

我的最终目标是在1-32,40,45,47,49-51上输出“特定字段为空白”的消息

如果这是最终目标,那么通过像List这样的中间表示没有意义 – 只需使用StringBuilder 。 您将以这种方式节省内存和CPU。

StringBuilder服务于您的目的,因此,如果您需要行号,您可以轻松更改代码。

取决于您如何/想要破坏代码。

鉴于您按行顺序阅读它,不确定您是否需要列表。 您当前所需的输出意味着在完全扫描文件之前无法输出任何内容。 文件的大小表明一次通过分析阶段也是一个好主意,因为你将使用缓冲输入,而不是将整个事物读入内存。

我会用一个枚举来描述这个问题,例如Field ??? 是空白然后使用它作为字符串构建器的字典键。

无论如何,作为第一个想法

你的输出是否应该是人类可读的? 如果是这样,在您的数据结构出现任何性能/内存问题之前,您将达到合理读取的限制。 使用最简单的方法来处理。

如果输出应该是机器可读的,那么该输出可能会建议适当的数据结构。

正如其他人所指出的,我可能会使用StringBuilder 。 列表可能需要多次resize ; StringBuilder的新实现不必resize。