Search code examples
c#findline

Can I copy line above my find line in output?


I have a little problem with duplicates lines above my found line. if (value1.StartsWith("***") & value1.EndsWith("useky")) with this code I find line but I would like to view line above this . Is there some code for it? I'd like console to write a line aboveConsole.WriteLine(lineabovefind); and I will copy wanted line. Thank you for every piece of advice


Solution

  • This requires you to enumerate your collection use plain old index advance method:

    var lines = new string[]{"whatever", "else", "***useky"};
    
    for (var i = 0; i < lines.Length; i++) {
        var thisLine = lines[i];
        if (i > 0 && thisLine.StartsWith("***") && thisLine.EndsWith("useky")) {
            Console.WriteLine(lines[i-1]);
        }
    }
    

    The code above will print 'else'.