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

如何在C#中将CSV的两行数据重排为键值对格式字符串

C# 处理双行CSV生成指定格式输出方案
  • 实现逻辑很简单,不需要引入第三方CSV处理库,原生方法就能搞定:
    1. 读取CSV前两行内容,分别作为键行和值行
    2. 按分隔符;拆分两行,过滤末尾空字段(适配原数据行尾带多余分号的场景)
    3. 按索引配对键和值,拼接为要求的格式后用顿号连接
  • 可直接运行的完整代码:
using System;
using System.Linq;
using System.IO; // 读取本地CSV文件时需要引入

class Program
{
    static void Main()
    {
        // 若读取本地CSV文件,替换为下行代码即可
        // string[] csvLines = File.ReadAllLines(@"你的CSV文件路径.csv").Take(2).ToArray();
        string[] csvLines = { "a;b;c;d;e;", "1;2;3;4;5;" };

        // 拆分字段并过滤空值,适配行尾多余分号的场景
        var keys = csvLines[0].Split(';', StringSplitOptions.RemoveEmptyEntries);
        var values = csvLines[1].Split(';', StringSplitOptions.RemoveEmptyEntries);

        // 配对键值拼接输出
        var output = string.Join("、", keys.Zip(values, (key, val) => $"{key}={val};<code>enter code here</code>"));
        
        // 输出结果验证
        Console.WriteLine(output);
    }
}
  • 运行后输出完全匹配要求:a=1;<code>enter code here</code>、b=2;<code>enter code here</code>、c=3;<code>enter code here</code>、d=4;<code>enter code here</code>、e=5;<code>enter code here</code>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:51:03