我正在阅读包含数百万行的多个文件,我正在创建一个包含特定问题的所有行号的列表。例如,如果特定字段留空或包含无效值。
所以我的问题是跟踪可能超过一百万行的数字列表最有效的日期类型。使用String Builder,Lists或其他什么方法会更有效吗?
我的最终目标是输出一条消息,例如“特定字段在1-32,40,45,47,49-51等处是空白的。所以在String Builder的情况下,我会检查以前的值如果它只有1个,我会把它从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++;
}
}
答案 0 :(得分:5)
我的最终目标是在1-32,40,45,47,49-51上输出“特定字段为空白”等消息
如果这是最终目标,那么通过List<int>
之类的中间代表也没有意义 - 只需使用StringBuilder
。你将以这种方式节省内存和CPU。
答案 1 :(得分:3)
取决于您如何/想要破坏代码。
鉴于您是按行顺序阅读,不确定您是否需要列表。 您当前所需的输出意味着在完全扫描文件之前无法输出任何内容。文件的大小表明一次通过分析阶段也是一个好主意,因为你将使用缓冲输入而不是将整个事物读入内存。
我会用枚举来形容这个问题,例如Field ???是空白然后将其用作字符串构建器字典的关键字。
无论如何首先想到
答案 2 :(得分:2)
StringBuilder符合您的目的,因此如果您需要行号,则可以轻松更改代码。
答案 3 :(得分:2)
你的输出是否应该是人类可读的?如果是这样,在数据结构出现任何性能/内存问题之前,您将达到合理读取的限制 long 。使用最容易使用的任何东西。
如果输出应该是机器可读的,那么该输出可能会建议适当的数据结构。
答案 4 :(得分:2)
正如其他人所指出的那样,我可能会使用StringBuilder
。列表可能需要多次 调整大小 ; StringBuilder
的新实现不必调整大小。