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

.NET控制台产品管理项目:搜索指定产品返回全部条目问题求助

产品搜索功能修复:只返回匹配项而非全部产品

问题原因

搜索逻辑中,当确认存在目标产品名称后,直接遍历整个字典输出所有产品条目,未做匹配过滤,导致无论搜索哪个产品,只要存在就会显示全部已创建产品。

修复后的搜索代码

替换原搜索部分的代码为以下内容:

case ConsoleKey.D2:
case ConsoleKey.NumPad2:
    Console.Write("Ange produkt namn: ");
    nameOfProduct = Console.ReadLine();
    // 遍历字典,仅输出名称匹配的产品
    foreach (KeyValuePair<int, string> s in products)
    {
        // 可选:添加StringComparison.OrdinalIgnoreCase实现忽略大小写匹配
        if (s.Value == nameOfProduct)
        {
            Console.WriteLine("Namn: " + s.Value + "\nArtikelnummer: " + s.Key);
        }
    }
    Console.ReadKey(true);
    break;

额外体验优化

如果需要处理搜索不到产品的场景,可以添加提示逻辑:

case ConsoleKey.D2:
case ConsoleKey.NumPad2:
    Console.Write("Ange produkt namn: ");
    nameOfProduct = Console.ReadLine();
    bool hasMatch = false;
    
    foreach (KeyValuePair<int, string> s in products)
    {
        if (s.Value.Equals(nameOfProduct, StringComparison.OrdinalIgnoreCase))
        {
            Console.WriteLine("Namn: " + s.Value + "\nArtikelnummer: " + s.Key);
            hasMatch = true;
        }
    }

    if (!hasMatch)
    {
        Console.WriteLine("Ingen produkt hittades med det angivna namnet.");
    }
    Console.ReadKey(true);
    break;

性能优化建议

若后续产品数量较多,按名称遍历搜索效率较低,可调整数据结构:使用Dictionary<string, List<int>>(键为产品名称,值为对应商品ID列表),这样能直接通过名称键快速查找匹配的商品ID,避免全字典遍历。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 06:50:24