在线性系列书籍中查找第 n 本书

本文关键字:查找 本书 线性 系列 | 更新日期: 2023-09-27 18:35:59

所以我有这张图表,里面有我正在迭代并打印出来的书籍。

public class Books : IBookFinder
{
    private Books(Books next, string book)
    {
        Next = next;
        Book = book;
    }
    public Books Next { get; }
    public string Book { get; }
    public Books Previous(string book)
    {
        return new Books(this, book);
    }
    public static Books Create(string book)
    {
        return new Books(null, book);
    }
    //This is the method I'm especially interested in implementing
    public string FromLeft(Books books, int numberFromLeft)
    {
        Console.Writeline("This is FromLeft method");
    }
}

一切都很好,但我想实现一个方法 FromLeft,这样我就可以在给定数字输入的情况下从它在图形中的位置写出书名。例如,如果输入"3",则应输出"暮光之城"。

class Program
{
    static void Main(string[] args)
    {
        var curr = Books
            .Create("Harry Potter")
            .Previous("Lord of the Rings")
            .Previous("Twilight")
            .Previous("Da Vinci Code");
        while (curr != null)
        {
            if (curr.Next != null)
            {
                Console.Write(curr.Book + " --- ");
            }
            else
            {
                Console.WriteLine(curr.Book);
            }
            curr = curr.Next;
        }
        Console.WriteLine("Input number to pick a book");
        var bookNumber = Console.ReadLine();
        int n;
        if (int.TryParse(bookNumber, out n)) //Checking if the input is a #
        {
        }
        else
        {
            Console.WriteLine("Input was not a number!");
        }
        Console.WriteLine(bookNumber);
        Console.ReadLine();
    }
}

关于我如何进行此操作的任何提示?

在线性系列书籍中查找第 n 本书

创建一个遍

历书籍 x 次的方法。

private Books FromLeft(Books book, int x){
    for(var i = 1; i < x; i++){
        book = book?.next;  // Check for null if you're not using C#6
    }
    return book;
}

如果您拿错了书,您可能需要更改一些数字。

递归!!哈哈

private Books FromLeft(Books book, int x){
    if(x-- > 0) return FromLeft(book?.Next, x); // Check for null if you're not using C#6
    return book;
}

得到上一个:(我不知道让你的类静态有多难)

public static class Books : IBookFinder
{
    private Books(Books next, string book, Books previous)
    {
        Next = next;
        Book = book;
        Previous = previous;
    }
    public Books Next { get; }
    public Books Previous { get; }
    public string Book { get; }
    public static Books Previous(this Books previous, string book)
    {
        return new Books(this, book, previous);
    }
    public static Books Create(string book)
    {
        return new Books(null, book, null);
    }
    private Books FromLeft(Books book, int x){
        if(x-- > 0) return FromLeft(book?.Next, x); // Check for null if you're not using C#6
        return book;
    }
    private Books FromRight(Books book, int x){
        if(x-- > 0) return FromRight(book?.Previous, x); // Check for null if you're not using C#6
        return book;
    }
}