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

时间:2016-12-10 11:49:42

标签: c# arrays list search logbook

我作为学校的作业在日志上工作,我已经到了如下所示。我正在努力解决一些需要实施的问题,我最关心的是理解为什么我需要列表中的数组。

我被告知要使用:

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

我的功能是,我想能够保存新帖子,至少包含一个标题和一条消息。日志被假定为List,并且每个日志都被假定为一个数组。

所以我的问题就是我正朝着正确的方向前进,有人请帮助我理解为什么它必须是列表中的数组。另外,在搜索部分时,请随时帮助我找到正确的方向,我希望能够在帖子中搜索日期,标题或单个单词。

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

3 个答案:

答案 0 :(得分:3)

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

虽然C#允许您将数组存储在列表中,但存储双元素数组的问题是这些数组的内容不对称:logBook[i][0]始终是标题,而logBook[i][1]始终是一条消息。

最好为帖子创建一个具有TitleMessage属性的类,并使用它而不是数组:

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

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

答案 1 :(得分:1)

像dasblinkenlight所说,使用课程更好。所以我完全赞同他。

但....为您的解决方案。您的列表和数组存在问题。

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

就我阅读你的帖子而言,每个列表项应该有一个新的数组。我以一段代码为例:

> 1 + [2,3,4]
<interactive>:8:1: error:
    • Non type-variable argument in the constraint: Num [t]
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall t. (Num [t], Num t) => [t]

> 1 + sum [2,3,4]
10

这样就不需要全局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; 数组。该列表将保留对您添加的数组的引用。

这是不正确的......你迭代日志(数组列表)并且你反复检查相同的logitem。 (变量logg永远不会改变)

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.");
}

随时提出更多信息

答案 2 :(得分:0)

即使我没有通过编辑或更改日志来解决问题,甚至删除日志,这也是最终归结为......我明天可能会这样做: )

    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.
            }