【问题标题】:C# how to write the whole array if a string within "array[1]" contains keyword如果“array [1]”中的字符串包含关键字,C#如何编写整个数组
【发布时间】: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


【解决方案1】:

或许你可以这样做:

var result = loggbok.FirstOrDefault(x=> x.Any(s=> s.Contains(key));

Console.WriteLine(result?? "No record found");

【讨论】:

  • 我可以以与我的代码类似的方式执行此操作吗?我是编程新手,当我超出我的知识库时我会感到困惑。
  • @Gobban 好的,试试这个,在你的 switch 而不是循环中,看看结果。你需要 System.Linq
【解决方案2】:

你甚至不需要循环,所以你需要做的就是通过索引从 loggbok 中检索项目。

// assign loggbokx of index 1, to variable item.
string[] item = loggbok[1];
// item will then have the 2nd (index=1) logbook.
// Note that index starts from 0.
// If you want to have the first one, then it should be loggbox[0]
// to make it even simpler you can write 
//     var item = loggbok[1];

// and the rest is the same...

//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++;
    }  
}

【讨论】:

  • 我试过了,但它只给了我索引 [x] 处的字符串,否则听起来不错。我认识的简单和代码。我需要的是循环数组,以便 if 语句可以访问 log[1] 中的字符串
  • 在“步入”中我试图访问的内容称为“新 System.Collections.Generic.Mscorlib_CollectionDebugView(loggbok).Items[0][1]”
【解决方案3】:

让我们做对吧!

为您的日志创建一个模型类:

class LogEntry
{
    public DateTime Date { get; set; }
    public string Title { get; set; }
    public string Post { get; set; }

    public override string ToString()
    {
        return "Date: " + Date.ToLongDateString() + " Kl: " + Date.ToShortTimeString()
            + "\tTitle: " + Title + "\tPost: " + Post;
    }
}

现在我们可以轻松地使用这个模型了。

让我们用更多记录填充列表:

List<LogEntry> loggbok = new List<LogEntry>();

for (int i = 0; i < 5; i++)
{
    LogEntry entry = new LogEntry();
    entry.Date = DateTime.Now;
    entry.Title = "title" + i;
    entry.Post = "post" + i;

    loggbok.Add(entry);
}

让我们打印出来:

foreach (var entry in loggbok)
    Console.WriteLine(entry);

由于ToString 方法重载,输出看起来不错。

我们来找点东西吧:

string key = "title3";
var found = loggbok.Find(log => log.Title == key);
Console.WriteLine("Found:\n" + found);

我们可以使用List类的不同methods,以及LINQ扩展方法。


如果您需要将数据保存到文件中,然后从那里读取,可以使用 json 序列化。

例如,让我们使用JavaScriptSerializer(不要忘记添加对程序集的引用):

JavaScriptSerializer jss = new JavaScriptSerializer();

// Save
File.WriteAllText("test.txt", jss.Serialize(loggbok));

// Load
loggbok = jss.Deserialize<List<LogEntry>>(File.ReadAllText("test.txt"));

【讨论】:

    【解决方案4】:

    如果有人觉得它很有趣,这就是解决方案。

    foreach (string[] item in loggbok)
    {
       foreach (string s in item)
       {
          //This was the magic line.
          string searchTitle = item[1].ToLower();
    
          if (searchTitle.Contains(titleKey.ToLower()))
          {
             Console.WriteLine("\n\tSearch hit #" + index);
    
             foundItem = true;
    
             Console.WriteLine(String.Join("\r\n", item));
    
             index++;
    
             break;
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多