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

C#如何在其他方法中搜索Main方法内定义的List<T>中的目标元素

解决方案

核心问题说明

你现在遇到的两个核心问题:

  • 变量作用域限制:定义在Main方法内的pokemonlist是局部变量,只能在Main方法内部访问,其他方法默认无法读取
  • 硬编码判断冗余:手动写151个if-else不仅重复代码多,后续修改维护成本极高

最优实现方案

我们只需要做两处核心修改即可解决所有问题,全程不需要写大量if判断:

步骤1:调整宝可梦列表的作用域

两种可选方案,选其中一种即可:

方案A:将列表提升为Program类的静态字段(新手更易上手)

修改Program类结构,把宝可梦列表定义为类的静态成员,所有静态方法都可以直接访问:

namespace Pokedex
{
    class Program
    {
        // 新增:静态宝可梦列表,所有静态方法可访问
        static List<Pokemon> pokemonList = new List<Pokemon>();

        public static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Gray ;
            
            // 这里直接给上面的静态列表赋值,不要重新定义局部变量
            pokemonList.Add(new Pokemon() { PokemonId = "001", PokemonName = "Bulbasaur", PokemonType = "Grass & Poison", PokemonCategory = "Seed Pokémon", PokemonDescription = "It bears the seed of a plant on its back from birth. The seed slowly develops. Researchers are unsure whether to classify Bulbasaur as a plant or animal. Bulbasaur are extremely tough and very difficult to capture in the wild." }) ;
            // 剩下的Add代码保持不变,全部添加到这个静态列表里
            // ...(其余宝可梦的添加代码省略)

            // 后续原有逻辑保持不变
            Welcome();
            AllFilterCategories();
            // ... 其余Main方法逻辑不变
        }
    }
}

方案B:调用搜索方法时传参(更符合方法封装规范)

不需要改静态字段,只需要修改搜索方法的签名,调用时把列表作为参数传入:

// Main方法中调用搜索方法的地方改成传参
case 1:
    NumberSearching(pokemonlist);
    break;
case 2:
    NameSearching(pokemonlist);
    break;

对应修改方法签名:

public static void NumberSearching(List<Pokemon> pokemonlist)
// 和
private static void NameSearching(List<Pokemon> pokemonlist)

步骤2:用LINQ查询替代大量if-else

首先需要在代码顶部引入LINQ命名空间:

using System.Linq;

然后改写两个搜索方法,只需要几行代码即可实现151只宝可梦的搜索,不需要写任何硬编码判断:

改写后的按编号搜索方法

public static void NumberSearching()
{
    Console.WriteLine("\nEnter the Number of the Pokémon you´re looking for.");
    string whichNumber = Console.ReadLine().Trim();
    
    // 直接从列表查询对应编号的宝可梦
    var targetPokemon = pokemonList.FirstOrDefault(p => p.PokemonId == whichNumber);

    if (targetPokemon != null)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        targetPokemon.AllInfos();
    }
    else
    {
        Console.WriteLine("未找到对应编号的宝可梦,请检查输入");
    }
    
    Console.ReadKey();
    Console.Clear();
    Program.SecondSearch();
}

改写后的按名称搜索方法

private static void NameSearching()
{
    Console.WriteLine("\nEnter the Name of the Pokémon you´re looking for.");
    string whichName = Console.ReadLine().Trim();
    
    // 忽略大小写匹配名称,输入大小写不影响搜索结果
    var targetPokemon = pokemonList.FirstOrDefault(p => 
        p.PokemonName.Equals(whichName, StringComparison.OrdinalIgnoreCase));

    if (targetPokemon != null)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        targetPokemon.AllInfos();
    }
    else
    {
        Console.WriteLine("未找到对应名称的宝可梦,请检查输入");
    }
    
    Console.ReadKey();
    Console.Clear();
    Program.SecondSearch();
}

额外优化建议

后续如果要录入151只宝可梦,也可以把宝可梦数据存到CSV、JSON等配置文件里,程序启动时批量读取加载,不用手动写151行Add代码,维护起来更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:36:03