如何通过线性搜索删除博客列表元素?解决‘i不存在’错误
问题分析与解决方案
错误原因
你在删除代码中使用的i是BlogSearch方法内部的循环局部变量,它的作用域仅限该方法内部,外部代码根本无法访问,因此编译器抛出“名称i在当前上下文中不存在”的错误。
具体解决办法
办法一:修改搜索方法返回索引(推荐)
把原BlogSearch方法改为返回找到的帖子索引,而非帖子内容,这样就能直接用索引调用RemoveAt完成删除:
static int BlogSearchIndex(List<string[]> myBlog, string searchedWord) { for (int i = 0; i < myBlog.Count; i++) { if (myBlog[i][0].ToUpper() == searchedWord.ToUpper()) return i; } return -1; // 返回-1代表未找到目标帖子 }
对应的删除逻辑修改为:
case 4: Console.Write("Write the title of the post you want to delete: "); string userInput = Console.ReadLine(); int postIndex = BlogSearchIndex(myBlog, userInput); if(postIndex == -1) { Console.WriteLine("The blogpost you wanted to delete wasn't found."); } else { myBlog.RemoveAt(postIndex); Console.WriteLine("Post deleted successfully."); } break;
办法二:直接使用List的Remove方法(无需修改原搜索方法)
你已经通过BlogSearch拿到了目标帖子的引用,直接调用List<T>.Remove()方法即可删除该元素(逻辑和原线性搜索一致,删除第一个匹配的帖子):
case 4: Console.Write("Write the title of the post you want to delete: "); string userInput = Console.ReadLine(); string[] postToDelete = BlogSearch(myBlog, userInput); if(postToDelete == null) { Console.WriteLine("The blogpost you wanted to delete wasn't found."); } else { myBlog.Remove(postToDelete); Console.WriteLine("Post deleted successfully."); } break;
办法三:保留原搜索方法,新增索引查询方法
如果不想改动原BlogSearch,可以单独写一个和它逻辑一致的索引查询方法:
static int GetPostIndex(List<string[]> myBlog, string searchedWord) { for (int i = 0; i < myBlog.Count; i++) { if (myBlog[i][0].ToUpper() == searchedWord.ToUpper()) return i; } return -1; }
后续删除逻辑和办法一完全一致,调用这个方法获取索引后执行删除即可。
内容的提问来源于stack exchange,提问作者sam_the_man
相关产品推荐
相关产品推荐

