You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#遍历列表查找字符串未找到提示重复输出 不使用LINQ如何修复

问题根源

你的代码把结果打印逻辑写在了遍历循环内部,每遍历一个列表元素就会执行一次判断和打印,哪怕后面还有其他元素没检查,也会直接输出当前次的匹配结果,才会出现每遍历一个索引就打印一次「未找到」的问题。

修复方案

你只需要新增一个状态标记记录是否找到匹配项,遍历过程中只处理「找到」的逻辑,遍历完全部元素后再判断是否需要打印「未找到」即可:

  • 定义bool类型的标记变量isFound,初始值为false,用于记录遍历全程是否匹配到目标用户名
  • 遍历过程中如果匹配到目标,就把isFound设为true,打印找到提示,可主动break终止后续无意义的遍历
  • 整个遍历结束后,再判断isFound的状态,如果仍然为false,才打印一次未找到提示

修正后完整代码

using System;
using System.Collections.Generic;

namespace exercise_74
{
    class Program
    {
        public static void Main(string[] args)
        {
            List<string> name = new List<string>();
            while (true)
            {
                string input = Console.ReadLine();
                if (input == "")
                {
                    break;
                }
                name.Add(input);
            }
            Console.WriteLine("who are u looking for ");
            string username = Console.ReadLine();
            int a = 0;
            bool isFound = false; // 新增匹配标记
            while (a < name.Count)
            {
                if (name[a] == username)
                {
                    Console.WriteLine(username + " was found");
                    isFound = true;
                    break; // 匹配到就提前退出循环,不需要继续遍历
                }
                a++;
            }
            // 遍历完所有元素后再判断是否未找到
            if (!isFound)
            {
                Console.WriteLine(username + " was not found");
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者thugcat85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:54:00