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

如何在C#中从字符串列表中筛选以特定字母开头的元素?

筛选C#列表中以特定字母开头的字符串

嘿,我来帮你搞定这个需求!首先先提个小细节:你原代码里的foreach循环写的Console.WriteLine(name)会报错哦,应该改成Console.WriteLine(n)——毕竟循环里的变量是n嘛😉

接下来,针对你要筛选以特定字母开头的姓名的需求,我给你两种常用方案,包括你提到的LINQ方法,以及手动筛选的方式:

方案1:使用LINQ(最简洁的方式)

LINQ的Where方法可以快速帮你过滤列表元素,配合StartsWith就能轻松实现按起始字母筛选。这里还要注意大小写兼容和空输入处理,避免程序出错:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        var list = new List<string>(); 
        int count = 1; 
        for (int i = 0; i < 5; i++) 
        { 
            Console.WriteLine("Enter name {0}", count++); 
            var name = Console.ReadLine(); 
            list.Add(name); 
        }

        // 获取用户要筛选的起始字母,做合法性检查
        Console.WriteLine("\nEnter the starting letter to filter names:");
        string input = Console.ReadLine().Trim();
        if (string.IsNullOrEmpty(input) || input.Length != 1 || !char.IsLetter(input[0]))
        {
            Console.WriteLine("Oops, please enter a single valid letter!");
            return;
        }
        char targetLetter = char.ToUpper(input[0]);

        // LINQ筛选:忽略大小写,同时跳过空/空白姓名
        var filteredNames = list.Where(name => 
            !string.IsNullOrWhiteSpace(name) && 
            name.Trim().StartsWith(targetLetter.ToString(), StringComparison.OrdinalIgnoreCase));

        // 输出结果
        Console.WriteLine($"\nNames starting with '{targetLetter}':");
        foreach (var n in filteredNames) 
        { 
            Console.WriteLine(n); 
        }
    }
}

代码说明:

  • string.IsNullOrWhiteSpace(name):避免空字符串或全空白的姓名导致的异常
  • StringComparison.OrdinalIgnoreCase:让筛选不区分大小写(比如输入"A"能匹配"Alice"和"alice")
  • 输入合法性检查:确保用户输入的是单个字母,避免程序崩溃

方案2:手动循环筛选(不使用LINQ)

如果你不想依赖LINQ,也可以用传统的循环手动过滤:

// 在获取targetLetter之后,替换LINQ部分为:
List<string> filteredNames = new List<string>();
foreach (var name in list)
{
    if (!string.IsNullOrWhiteSpace(name) && 
        name.Trim().StartsWith(targetLetter.ToString(), StringComparison.OrdinalIgnoreCase))
    {
        filteredNames.Add(name);
    }
}

// 后续输出逻辑和方案1一致

这种方式逻辑更直观,适合刚接触C#的开发者理解。

内容的提问来源于stack exchange,提问作者Ferrad Rosé

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:18:01