我有一个文本文件,应该有100行。每行由id(001,002,003等)标识。但有时一些线路会错过。例如:某些文本文件可能只有93行。我正在检查缺失的行。
这是我的代码。
bool[] idCheck = new bool[100];
for (int i = 0; i < 100; i++)
{
idCheck[i] = false;
for (int j = 0; j < FileIdArray.Length; j++) //FileIdArray is the list of all my Ids.
{
if (i == Convert.ToInt32(FileIdArray[j]))
{
idCheck[i] = true;
}
}
}
ResultBuilder.AppendLine(String.Format("*****************************************"));
for (int i = 0; i < idCheck.Length; i++)
{
idCheck[0] = true;
if (idCheck[i] == false)
{
ResultBuilder.AppendLine(String.Format("Missing Id's from File 1 are {0}", i));
}
}
我的o / p看起来像这样:
*****************************************
Missing Id's from File 1 are 26
Missing Id's from File 1 are 41
Missing Id's from File 1 are 56
Missing Id's from File 1 are 88
Missing Id's from File 1 are 94
Missing Id's from File 1 are 98
Missing Id's from File 1 are 99
我喜欢我的o / p看起来像这样:
Missing Id's from File 1 are 26,41,56,88,94,98,99.
我意识到我将ResultBuilder
置于循环中,因此我重复了。但是当我尝试将i
保存到字符串时,我得到了一个异常。
答案 0 :(得分:1)
您可以用以下内容替换底部循环:
var missing = idCheck.Select((b, idx) => new { IsPresent = b, Idx = idx })
.Where(p => !p.IsPresent)
.Select(p => p.Idx);
string message = string.Format("Missing ids from File 1 are {0}", string.Join("," missing));
ResetBuilder.Apppend(message);
答案 1 :(得分:0)
尝试以下代码,这将保存您的第二个循环。在第一个循环中,您将获得缺少的条目。
for (int i = 0; i < 100; i++)
{
idCheck[i] = false;
for (int j = 0; j < FileIdArray.Length; j++) //FileIdArray is the list of all my Ids.
{
if (i == Convert.ToInt32(FileIdArray[j]))
{
idCheck[i] = true;
break;
}
}
if(j>=100)
ResultBuilder.AppendLine(String.Format("Missing Id's from File 1 are {0}", i));
}
答案 2 :(得分:0)
更新您的代码:
ResultBuilder.AppendLine(String.Format("Missing Id's from File 1 are:" )
for (int i = 0; i < idCheck.Length; i++)
{
idCheck[0] = true;
if (idCheck[i] == false)
{
ResultBuilder.Append(String.Format("{0}", i));
}
}
答案 3 :(得分:-1)
只需在for循环中使用以下行: -
ResetBuilder.Append(String.Format("Missing Id's from File 1 are {0}", i)) ;