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

C#如何通过搜索字符串获取CSV文件中匹配的整行数据?

实现思路
  • 直接使用.NET内置的文件读取API加载CSV文件所有行,无需引入第三方依赖,适合新手快速实现
  • 跳过第一行表头后遍历每一行数据,按逗号拆分后匹配目标字段(示例默认匹配第二列Name,可按需调整)
  • 匹配成功后直接返回拆分后的数组,无匹配结果返回空数组
完整代码示例
using System;
using System.IO;

class CsvSearchDemo
{
    // 方法入参:csv文件路径、要搜索的用户名
    public static string[] SearchUserByName(string csvFilePath, string targetName)
    {
        // 先判断文件是否存在
        if (!File.Exists(csvFilePath))
        {
            Console.WriteLine("CSV文件不存在");
            return Array.Empty<string>();
        }

        // 读取CSV所有行
        string[] allLines = File.ReadAllLines(csvFilePath);

        // 从第二行开始遍历(跳过表头)
        for (int i = 1; i < allLines.Length; i++)
        {
            string line = allLines[i].Trim();
            if (string.IsNullOrEmpty(line)) continue;

            // 按逗号拆分当前行
            string[] fields = line.Split(',');
            // 确保字段数正确(示例CSV是3列)
            if (fields.Length < 3) continue;

            // 匹配Name列(第二列,索引为1),忽略大小写,适配输入Toby匹配csv里的toby的场景
            if (fields[1].Equals(targetName, StringComparison.OrdinalIgnoreCase))
            {
                return fields;
            }
        }

        // 无匹配结果返回空数组
        return Array.Empty<string>();
    }

    static void Main(string[] args)
    {
        // 调用测试
        string[] userInfo = SearchUserByName("users.csv", "Toby");
        if (userInfo.Length > 0)
        {
            Console.WriteLine("匹配到的用户信息:");
            foreach (var field in userInfo)
            {
                Console.WriteLine(field);
            }
            // 输出结果为 2 toby foo
        }
        else
        {
            Console.WriteLine("未找到匹配的用户");
        }
    }
}
注意事项
  • 以上实现仅适用于字段内不包含逗号、引号的简单CSV文件,如果你后续需要处理更复杂的CSV格式,可以使用.NET生态常用的CSV处理类库简化开发
  • 如果需要搜索其他字段,修改匹配时的fields索引即可,比如要匹配Id列就改为fields[0]
  • 需要严格区分大小写匹配的话,删掉Equals方法里的StringComparison.OrdinalIgnoreCase参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:06:02