【发布时间】:2016-11-06 05:02:00
【问题描述】:
我正在创建一个由列表内的数组组成的日志,数组是每个新条目,列表是日志。到目前为止,这是我尝试解决的方法:
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 个组合到列表中,这样它们就成为列表中的一个元素,所以当我搜索标题时,它们会出现作为一个团队。
我在声明日志时尝试使用普通字符串列表,但是我无法将数组添加到其中而无需指定要插入的索引。当我将列表的类型更改为 string[] 时,foreach 循环停止工作,因为它们无法将 string[] 转换为字符串,所以我将 foreach 循环内的字符串更改为 string[],现在所有当我尝试写出所有内容或搜索“System.String[]”时,我得到了。
这就是我现在所处的位置,所以如果有人能告诉我我做错了什么或告诉我如何解决这个问题,我将不胜感激。
【问题讨论】:
-
我建议创建一个
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" }).Contains("b")返回 false,因为该数组不包含"b"字符串。
标签: c# arrays list search foreach