【问题标题】:Previous or next line through the current line index通过当前行索引的上一行或下一行
【发布时间】: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.IndexOutOfRa‌​ngeException' 类型的未处理异常”,并且不知道如何将其与上面的代码结合使用。

编辑:

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#


    【解决方案1】:

    我建议使用Linq 扩展方法SkipFirst

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

    你需要注意边界条件,我留给你补充。 (例如,如果 i=0 则不会有任何先前的元素)。

    看看这个Demo,你会明白的。

    【讨论】:

    • _你好,谢谢你的反馈,我是 C# 新手,你能在我的例子中告诉我如何将它与上面的主要代码结合起来吗?
    • @zrubi 查看演示,你就会明白了。
    • 完全符合我的需要,我已经为我上面的案例添加了您的解决方案,但仍然有关于索引超出范围的相同错误,如果下一行为空,不知道如何避免这个错误
    猜你喜欢
    • 2010-11-18
    • 2020-12-17
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多