【发布时间】:2016-11-13 12:32:43
【问题描述】:
我当前的代码正在遍历一个包含数组中已保存字符串的列表。目前它会查找该数组中的所有字符串。我想更改它,使其仅通过(搜索、查找)“log [1]”中的字符串
抱歉,我不知道“log[1]”这个词。我是编程新手。继续阅读,我想你会明白的。
这就是我想要的方式:
foreach (string[] item[1] in loggbok)
item[1] 是 log[1]。数字 1 非常重要,因为我只想在 log[1] 内搜索。
这是我当前将整个数组保存在列表中的代码:
List<string[]> loggbok = new List<string[]> { };
string[] log = new string[3]; //date, title, post
DateTime date = DateTime.Now;
log[0] = "\n\tDate: " + date.ToLongDateString() + " Kl: " + date.ToShortTimeString();
Console.WriteLine(log[0]);
Console.Write("\tTitle: ");
log[1] = "\tTitle: " + Console.ReadLine();
Console.Write("\tPost: ");
log[2] = "\tPost: " + Console.ReadLine();
loggbok.Add(log);
log = new string[3];
我保存“log[1],log[2],log[3]”
下面的代码我想创建一个搜索函数,它遍历我的列表并识别 log[1] aka 标题中的所有字符串。如果字符串标题包含用户关键字,则所有日志都应加入并打印日志。
到目前为止。我通过搜索所有日志(1,2,3)解决了这个问题。这意味着我的程序当前正在搜索(标题、日期、帖子)中的字符串。这样一来,当我希望仅通过搜索标题来限制用户时,您就可以搜索消息或“发布”。
所以我认为如果在我的 foreach 循环中我将“item”设置为“item[1]”。这会使我的代码只查找“log [1]”。虽然写“item[1]”是无效的语法,但我没有走那么远。
当前搜索功能:
string key;
Console.Write("\n\tSearch: ");
key = Console.ReadLine();
//Searching through all log[] in loggbok.
//I want to change this line to item[1]
foreach (string[] item in loggbok)
{
//goes deeper and looks for all strings within log[].
foreach (string s in item)
{
//if a string is found containing key word, this block will run.
if (s.Contains(key))
{
foundItem = true;
Console.WriteLine(String.Join("\r\n", item));
index++;
}
}
}
【问题讨论】:
-
好的,这个怎么样?
-
我不想写一堵文字墙,但由于我是一个业余程序员,我不知道正确的词来使这个问题更容易问。可能这是广泛的,如果是这样我道歉。不过,我希望这能让我更容易理解我的问题。
-
我还尝试将标题更改为更合适。我不知道我在 C# 中所说的“log [1]”是什么。它是元素、数组还是数组成员?我不知道。当我知道它叫什么时,我可以编辑它。
标签: c# arrays list foreach element