【发布时间】:2016-08-16 12:10:04
【问题描述】:
我正在尝试找出如何通过此代码的当前行索引获取上一行或下一行。
程序只是将行写入文本文件,但如果行已经存在,我想查找并读取存在行,但通过存在行的当前索引获取上一行或下一行。
如果当前是不可分的,则为下一行,如果可分,则为上一个,以获得此结果,例如我的文本文档内容:
if exist is "phrase1" it is indivisible index so show me: "phrase2"
if exist is "phrase2" it is divisible index so show me: "phrase1"
if exist is "phrase3" it is indivisible index so show me: "phrase4"
if exist is "phrase4" it is divisible index so show me: "phrase3"
if exist is "phrase5" it is indivisible index so show me: "phrase6"
为了清楚起见,我再次将不可分割的索引称为 1、3、5、7、9 等,因此,如果文本文档中存在与不可分割索引号位于同一行的行,在这种情况下,我想要获取下一行。如果是 2、4、6、8 等,我想获得上一个。例如,如果存在找到的行与索引号 1 在线,我想从第 2 行获取输出短语,即 (+ 1) 到当前索引。但是如果存在找到的线位于索引 2 的线上,给我 1,(-1)到当前索引。如果 3,给我 4。如果 4,给我 3,等等
所以如果我以某种方式走这条路:
string [] allLines = File.ReadAllLines("testFile.txt");
for (int i = 0; i < allLines.Length-2; i++)
{
if ((i+1) % 2 == 0)
{
Console.WriteLine("Next Line: " + allLines[i+2]);
}
else
{
Console.WriteLine("Previous Line: " + allLines[i-1]);
}
}
我收到错误“03_WORKFILE.exe 中发生'System.IndexOutOfRangeException' 类型的未处理异常”,并且不知道如何将其与上面的代码结合使用。
编辑:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
string[] allLines = new string[]
{
@"word1",
@"word2",
@"word3",
@"word5",
@"word6"
};
string input = "word6";
var index = Array.FindIndex(allLines, line => line == input);
Console.WriteLine(index);
if (index % 2 == 0)
{
Console.WriteLine("Next Line : " + allLines.Skip(index + 1).First());
}
else
{
Console.WriteLine("Previous Line : " + allLines.Skip(index - 1).First());
}
Console.Read();
}
}
【问题讨论】:
标签: c#