在一個專案中,我正在制作一個“博客”,將博客文章放入一個字串陣列中,然后將其傳輸到一個串列陣列中。這是我當前的代碼,我很感激任何幫助。我對 c# 和整個編程還是個新手,所以不確定如何解決它。
當前的問題是,在第 3 種情況下,我收到錯誤訊息:運算子“==”不能應用于“字串”和“字串[]”型別的運算元,并且名稱“i”在當前背景關系中不存在“帖子在博客中”代碼塊。
我在這里創建了一個最小的可重現示例,該程式唯一的其他功能是 1. 洗掉所有博客文章和 2. 列印出所有博客文章及其名稱和內容。
bool minBool = true;
List<string[]> blogPost = new List<string[]> { };
string[] post = new string[2];
while (minBool)
{
Console.WriteLine("\n\n\tWelcome to the blog!");
Console.WriteLine("\n\t[1] - Write a blogpost");
Console.WriteLine("\t[3] - Search for a blogpost");
Console.Write("\n\tChoice:");
Int32.TryParse(Console.ReadLine(), out int input);
switch (input)
{
case 1:
Console.Write("\tName your post: ");
post = new string[2];
post[0] = Console.ReadLine();
Console.Write("\tWrite your post: ");
post[1] = Console.ReadLine();
blogPost.Add(post);
break;
case 3:
string searchTerm = Console.ReadLine();
string result = "The blogpost doesn't exist";
foreach (string blog in blogPost)
{
if (searchTerm == blog)
{
result = $"\tThe post is in the blog: {post[i]}";
break;
}
}
Console.WriteLine(result);
break;
uj5u.com熱心網友回復:
問題是您試圖將searchterm變數 astring與blogpost變數的一個專案進行比較,該專案的型別為string[]。這是行不通的。
相反,您可以執行以下操作:
foreach(var blog in blogPost)
{
if(searchTerm == blog[0] || searchTerm == blog[1])
{
result = $"\tThe post is in the blog: {blog[0]}"; // Print blog name
break;
}
}
但是這樣您的搜索詞必須與帖子的名稱或內容完全相同。這對于快速搜索來說不是很方便。您可以使用該Contains()方法,而不是完全比較字串:
if(blog[0].Contains(searchTerm) || blog[1].Contains(searchTerm))
{
result = $"\tThe post is in the blog: {blog[0]}"; // Print blog name
break;
}
現在,您只需提供部分名稱或內容即可搜索博客文章。
請注意,只有滿足搜索詞的第一篇博客文章才會列印到控制臺。
考慮創建一個BlogPost類來將博客文章保存在List. 通過這種方式,您的代碼更具表現力且更易于處理:
public class BlogPost
{
public string Name { get; }
public string Content { get; }
public BlogPost(string name, string content)
{
Name = name;
Content = content;
}
}
然后像這樣保存:
private List<BlogPost> _blogPosts = new List<BlogPost>();
[...]
case 1:
Console.Write("\tName your post: ");
var name = Console.ReadLine();
Console.Write("\tWrite your post: ");
var content = Console.ReadLine();
_blogPosts.Add(new BlogPost(name, content));
現在您的搜索看起來像這樣:
foreach (var blog in _blogPosts)
{
if(blog.Name.Contains(searchTerm) || blog.Content.Contains(searchTerm))
{
result = $"\tThe post is in the blog: {blog.Name}"; // Print blog name
break;
}
}
有了博客文章課程,您現在變得更加靈活。例如,您可以為搜索博客文章等時應使用的關鍵字添加附加屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/341256.html
上一篇:當陣列的索引值不唯一時使用什么?
