2

我正在从文本文件中读取以查找某行以我的条件开头的行索引。
事实证明,我想要的标准实际上有两个实例,我想得到第二个。
我将如何修改以下代码以跳过第一个实例并获取第二个?

var linesB = File.ReadAllLines(In_EmailBody);
int LineNumberB = 0;
string criteriaB = "T:";
for (LineNumberB = 0; LineNumberB < linesB.Length; LineNumberB++){
    if(linesB[LineNumberB].StartsWith(criteriaB))
        break;
}

我使用之后的结果并将其与另一个标准进行比较,以找出两个结果之间的行数。

4

1 回答 1

4

您可以使用以下 LINQ 查询来简化您的任务:

List<string> twoMatchingLines = File.ReadLines(In_EmailBody)
    .Where(line = > line.StartsWith(criteriaB))
    .Take(2)
    .ToList();

现在您在列表中都有。

string first = twoMatchingLines.ElementAtOrDefault(0);  // null if empty
string second = twoMatchingLines.ElementAtOrDefault(1); // null if empty or only one

如果你想使用 for 循环(你的最后一句话建议它),你可以计算匹配的行:

int matchCount = 0;
for (int i = 0; i < linesB.Length; i++)
{
    if(linesB[i].StartsWith(criteriaB) && ++matchCount == 2)
    {
        // here you are
    }
}
于 2021-04-02T13:46:56.720 回答