为什么列表中有一个数组? C#

Why have an array in a list? C#

我正在做一个日志作为学校的作业,我已经做到了如下所示。我正在为一些需要实现的事情而苦苦挣扎,我最关心的是理解为什么我需要列表中的数组。

我被告知使用:

List logBook = new List { };
string[]post = new string [2]

功能是我假设能够保存新的 posts,至少有一个标题和一条消息。日志假设是一个列表,每个日志假设是一个数组。

所以我的问题只是我是否朝着正确的方向前进,有人可以帮助我理解为什么它必须是列表中的数组。另外,当涉及到搜索部分时,请随时在正确的方向上帮助我,我希望能够在 post.

中搜索日期、标题或单个单词
static void Main(string[] args) {
    string titel;
    string post;
    string[] logg = new string[20];

    List<string[]> logBook = new List<string[]> { };
    DateTime tiden = DateTime.Now;
    Console.WriteLine(tiden.ToShortDateString());

    bool go = true;

    while (go)
        try
        {
            Console.WriteLine("\n\tWelcome to the Logbook!\n");
            Console.WriteLine("\t[1] Write a new post");
            Console.WriteLine("\t[2] Search for a post");
            Console.WriteLine("\t[3] Display all posts");
            Console.WriteLine("\t[4] Quit");
            Console.Write("\n\tSelect from menu: ");

            int menyVal = Convert.ToInt32(Console.ReadLine());
            int i = 0;

            switch (menyVal)
            {
                case 1:
                    Console.WriteLine("\tWrite a title to your post: ");
                    titel= Console.ReadLine();

                    Console.WriteLine("\n\tWrite your post: ");

                    Console.WriteLine("\t" + tiden.ToShortDateString() + "\n");
                    Console.WriteLine("\t" + titel + "\t");
                    post = Console.ReadLine();
                    logg[i] = tiden.ToShortDateString() + "\n" + titel + "\n" + post + "\n";
                    logBook.Add(logg);
                    i = i + 1;
                    break;

                case 2:
                    Console.WriteLine("\tWrite a searchword or a date (yyyy-mm-dd)");
                    string keyword = Console.ReadLine();

                    foreach (var item in logBook)
                    {
                        if (logg[i] == keyword)
                            Console.WriteLine(logg[i]);
                        else
                            Console.WriteLine("Searchword couldn't be found.");
                    }
                    break;

                case 3:
                    Console.WriteLine("\tThese are the current posts in Logbook.\n ");
                    foreach (string[] element in logBook)
                    {
                        Console.WriteLine("\t" + element);
                    }

                    break;

                default:
                    Console.WriteLine("\tChoose from menu 1 - 4");
                    break;

                case 4:
                    go = false;
                    break;
            }
        }
        catch
        {
            Console.WriteLine("\tChoose from menu 1 - 4");
        }
    }
}

使用 List<T> 的想法是正确的。使用两个字符串数组(一个用于标题,一个用于消息)的想法是不正确的。

尽管 C# 允许您将数组存储在列表中,但存储 two-element 数组的问题在于这些数组的内容不对称:logBook[i][0] 始终是标题,而 logBook[i][1] 始终是一条消息。

最好用 TitleMessage 属性为 post 制作一个 class,并用它代替数组:

class LogPost {
    public string Title { get; set; }
    public string Message { get; set; }
}

List<LogPost>List<string[]> 更易读,它让您可以更易读的方式访问 logBook[i].TitlelogBook[i].Message

像dasblinkenlight 说的,最好用一个class。所以我完全同意他的看法。


但是....对于您的解决方案。您的列表和数组有问题。

您的实现方式是,您使用了一个字符串数组和一个列表。您将整个格式化字符串写为数组的一个元素。然后将整个数组添加到列表中。所以列表中的每一项都是同一个数组....

据我阅读您的 post,您应该为每个列表项创建一个新数组。我以一段代码为例:

switch (menyVal)
{
    case 1:
        Console.WriteLine("\tWrite a title to your post: ");
        // i'd rather declare the string here, so the code and declaration should stick together. (it's not the pascal language ;-))
        string titel= Console.ReadLine();

        Console.WriteLine("\n\tWrite your post: ");

        Console.WriteLine("\t" + tiden.ToShortDateString() + "\n");
        Console.WriteLine("\t" + titel + "\t");
        post = Console.ReadLine();

        // here comes the thing:
        // you are formatting it as one element and add that element to the list. 
        // ->> wrong   >>   logg[i] = tiden.ToShortDateString() + "\n" + titel + "\n" + post + "\n";
        // ->> logBook.Add(logg);

        // create an array per item....
        string[] arr = new string[2];
        arr[0] = title;
        arr[1] = post;

        logBook.Add(arr);

        //   i = i + 1;   not needed.
        break;

这样就不需要全局 logg 数组。列表将保留对您添加的数组的引用。


这是不正确的...您迭代日志(数组列表)并且一遍又一遍地检查同一个 logitem。 (变量 i 永远不会改变)

foreach (var item in logBook)
{
    if (logg[i] == keyword)
        Console.WriteLine(logg[i]);
    else
        Console.WriteLine("Searchword couldn't be found.");
}

您要找的是:

van anyFound = false;

foreach (var item in logBook)
{
    foreach(var element in item)
    {
        if(element == keyword)
        {
            foreach(var s in item)
            {
                Console.Write(s);
            }
            Console.WriteLine("");
            anyFound = true;
        }
    }
    if(!anyFound)
        Console.WriteLine("Searchword couldn't be found.");
}

或者简而言之:

var foundIn = logBook.Where(item => item.Contains(keyword));

foreach(var elements in foundIn)
    Console.WriteLine(string.Join(" ", elements);

欢迎询问更多信息

这就是最终的结果,即使我还没有通过编辑或在写入日志后更改日志或什至删除日志来解决问题...我也许可以做到明天:)

    List<string[]> logBook = new List<string[]> { };
        DateTime time = DateTime.Now;
        Console.WriteLine("\t" + time.ToShortDateString());
        Console.WriteLine("\n\tWelcome to the Logbook!\n");

        bool go = true;

        while (go)
            try
            {
                {
                    Console.WriteLine("");  //Skapar ny rad. Användaren ska inte känna att det blandar ihop sig.
                    Console.WriteLine("\t[1] Write a new post");
                    Console.WriteLine("\t[2] Search for a post");
                    Console.WriteLine("\t[3] Display all posts");
                    Console.WriteLine("\t[4] Quit");

                    Console.Write("\n\tSelect from menu: ");

                    int menu = Convert.ToInt32(Console.ReadLine());  //Gör om inmatad sträng till heltal.
                    Console.WriteLine("");  //Skapar mellanrum innan nästa direktiv till användaren (Estetiskt).

                    switch (menu)
                    {
                        case 1:

                            string timeDate = time.ToShortDateString();

                            Console.Write("\tWrite a title to your post: ");
                            string title = Console.ReadLine();

                            Console.Write("\n\tPost is created " + timeDate + "\n\n\tWrite your post: ");

                            //Console.WriteLine("\t" + timeDate + "\n");
                            //Console.WriteLine("\t" + title + "\n\t");
                            string post = Console.ReadLine();

                            string[] arr = new string[3];
                            arr[0] = timeDate;
                            arr[1] = title;
                            arr[2] = post;

                            logBook.Add(arr);
                            break;

                        case 2:
                            Console.Write("\tWrite a searchword or a date (yyyy-mm-dd): ");
                            string keyword = Console.ReadLine();
                            Console.WriteLine("");

                            bool anyFound = false;

                            foreach (string[] item in logBook)  //För varje element(item) i Listan(logBook) dvs (arr[i])
                            {
                                foreach (string element in item)  //För varje element(element) i arr[i] dvs (arr[0], arr[1], arr[2])
                                {
                                    if (element.Contains(keyword))  // Om arr[0], arr[1] eller arr[2] innhåller sökord....
                                    {
                                        foreach (string s in item)  // Skriv ut varje arr[i] i det elementet(item) (dvs hela den loggen)
                                        {
                                            Console.WriteLine("\t" + s);
                                        }
                                        Console.WriteLine("");
                                        anyFound = true;
                                    }
                                }
                            }
                            if (!anyFound)
                                Console.WriteLine("\tSearchword couldn't be found.");
                            break;

                        case 3:
                            Console.WriteLine("\tThese are the current posts in Logbook.\n ");

                            foreach (var item in logBook)  //För varje element(item) i Listan(logBook) dvs (arr[i])
                            {
                                foreach (string element in item)  //För varje element(element) i arr[i] dvs (arr[0], arr[1], arr[2])
                                {
                                    Console.WriteLine("\t" + element);
                                }
                                    Console.WriteLine("");
                            }
                            break;

                        default:
                            Console.WriteLine("\tChoose from menu 1 - 4");
                            break;

                        case 4:
                            go = false;
                            break;
                    }
                }
            }
            catch
            {
                Console.WriteLine("");  //Estetisk för att användaren ska få ny rad innan meddelandet.
                Console.WriteLine("\tChoose from menu by using number 1 - 4"); //Aktiveras om användaren knappar in annat än heltal.
            }