我正在创建一个由列表中的数组组成的日记,该数组是每个新条目和列表是日记。下面是我试图解决它迄今:字符串[]列表内部导致问题
using System;
using System.Collections.Generic;
using System.Linq;
namespace Journal
{
class Program
{
static void Main(string[] args)
{
int menuChoice = 0;
List<string[]> journal = new List<string[]>();
while (menuChoice != 4)
{
Console.WriteLine("\n\t\t===Journal===");
Console.WriteLine("\t[1] New entry in the journal");
Console.WriteLine("\t[2] Search entry in the journal");
Console.WriteLine("\t[3] Show contents of the journal");
Console.WriteLine("\t[4] Exit");
Console.Write("\tChoose: ");
int.TryParse(Console.ReadLine(), out menuChoice);
{
switch (menuChoice)
{
case 1:
{
string[] entry = new string[3];
DateTime time = DateTime.Now;
entry[0] = Convert.ToString(time);
Console.Write("\n\tWrite your title: ");
entry[1] = Console.ReadLine();
Console.Write("\n\tWrite your new entry: ");
entry[2] = Console.ReadLine();
journal.Add(entry);
}
break;
case 2:
Console.Write("\n\tSearch entry in the journal: ");
string searchTerm = Console.ReadLine();
for (int i = 0; i < journal.Count; i++)
if (journal[i].Contains(searchTerm))
{
Console.WriteLine(journal[i]);
}
else
{
Console.WriteLine("\n\tYour search was not found.");
}
break;
case 3:
Console.WriteLine("\n\tJournal:");
foreach (string[] item in journal)
Console.WriteLine("\n\t" + item);
break;
case 4:
break;
}
}
}
}
}
}
我已经试图使这项工作,它仍然没有带来很大的麻烦。我想要做的是在数组中使用3个索引空间作为时间,标题和文本,然后将这3个组合到列表中,以便它们成为列表中的单个元素,所以当我搜索标题时作为一个团队。
我试图在声明日记时使用正常的字符串列表,但不能将数组添加到它,而无需指定要插入的索引。当我将列表的类型更改为字符串[]时,foreach循环停止工作,因为它们无法将字符串[]转换为字符串,于是我将foreach循环内的字符串更改为字符串[],现在全部当我尝试写出所有内容或搜索“System.String []”时,我会得到它。
这就是我现在所处的位置,所以如果有人能告诉我我做错了什么,或者告诉我如何解决这个问题,我将非常感激。
我d建议创建一个'JournalEntry'类,而不是为此使用字符串数组。它会使你的代码更加容易处理:entry.Time,entry.Title和Entry.Content与entry [0],entry [1]和entry [2] '。 –
另外请注意,你不是调用'string.Contains',而是调用'Enumerable.Contains'(一个对数组,列表等集合进行操作的Linq方法)。这导致搜索检查条目的时间,标题或内容是否完全等于给定搜索词,而不是检查标题或内容是否包含搜索词。 '“abc”.Contains(“b”)'返回true,而'(new string [] {“abc”})。包含(“b”)返回false,因为该数组不包含“b”字符串。 –