zrubi zrubi - 3 months ago 17
C# Question

Previous or next line through the current line index

I'm trying to figure out how to get previous or next line through the current line index for this code.

Program just writes line to text file, but if line is already exist, I want find and read exist line, but get previous or next line through this current index of exist line.

Next line if current is indivisible, previous if divisible, to get this result, for example my text document content:

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"


For clarity again I call the indivisible indexes 1, 3, 5, 7, 9 etc., So if exist found line in text document located on line with indivisible index number, in this case I want get next line. if 2, 4, 6, 8 etc., I want get previous. For example, if exist found line is on line with index number 1, I want get on output phrase from line 2, in other words (+ 1) to current index. But if exist found line is located on line with index 2, give me 1, (-1) to current index. if 3, give me 4. if 4 give me 3, etc

so if I go somehow this way:

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]);
}
}


I got error "An unhandled exception of type 'System.IndexOutOfRa‌​ngeException' occurred in 03_WORKFILE.exe" and also not sure how to combine it with code above.

EDIT:

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();

}

}

Answer

I would suggest using Linq extension methods Skip and First.

string [] allLines = File.ReadAllLines("testFile.txt");

// if you found a match to the given string and 
// you know the index `i` for a matching string then...

var previousLine = allLines.Skip(i-1).FirstOrDefault();
var nextLine = allLines.Skip(i+1).FirstOrDefault(); 

You need to take care of border conditions, I'm leaving it to you to add. (ex. if i=0 then there won't be any previous element ).

Check this Demo, you'll get an idea.