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

C#如何将含IDictionary属性的对象序列化为用户友好的CSV文件

C# 字典属性CSV序列化/反序列化方案

推荐使用.NET生态成熟度最高的CSV处理库 CsvHelper,搭配自定义映射规则即可实现用户友好的读写效果,不需要额外开发复杂的类型转换器。


实现效果

生成的CSV模板会自动将字典的键展开为独立列,用户直接对应列填值即可,无需理解任何键值对格式:

Id,property1,property2,property3
示例ID,示例值1,示例值2,

实现步骤

1. 安装依赖

通过NuGet安装CsvHelper即可:

dotnet add package CsvHelper

2. 基础类定义

public class A
{
    public string Id { get; set; }
    public IDictionary<string, string> PropertiesTobeUpdated { get; set; } = new Dictionary<string, string>();
}

3. 生成CSV模板(序列化)

using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;

public void GenerateCsvTemplate(string outputPath, List<string> allowedProperties)
{
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        HasHeaderRecord = true,
        // 自动处理含特殊字符的单元格转义
        Escape = '"'
    };

    using var writer = new StreamWriter(outputPath);
    using var csv = new CsvWriter(writer, config);

    // 手动写入表头:Id + 所有允许更新的属性名
    csv.WriteField("Id");
    foreach (var prop in allowedProperties)
    {
        csv.WriteField(prop);
    }
    csv.NextRecord();

    // 写入示例数据,方便用户参考
    csv.WriteField("示例记录ID");
    foreach (var prop in allowedProperties)
    {
        csv.WriteField($"示例{prop}值");
    }
    csv.NextRecord();
}

allowedProperties 为你允许用户更新的属性列表(property1~propertyN),可从配置/数据库动态读取。

4. 解析用户填写的CSV(反序列化)

public List<A> ParseUserCsv(string inputPath)
{
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
        HasHeaderRecord = true,
        // 忽略未定义列,避免用户乱加列报错
        MissingFieldFound = null
    };

    using var reader = new StreamReader(inputPath);
    using var csv = new CsvReader(reader, config);
    var result = new List<A>();

    csv.Read();
    csv.ReadHeader();

    while (csv.Read())
    {
        var record = new A
        {
            Id = csv.GetField<string>("Id"),
            PropertiesTobeUpdated = new Dictionary<string, string>()
        };

        // 遍历所有表头列,除Id外全部加入字典
        foreach (var header in csv.HeaderRecord)
        {
            if (header.Equals("Id", StringComparison.OrdinalIgnoreCase)) 
                continue;
            
            var value = csv.GetField<string>(header);
            if (!string.IsNullOrWhiteSpace(value))
            {
                record.PropertiesTobeUpdated[header] = value;
            }
        }
        result.Add(record);
    }

    return result;
}

如果需要限制仅允许用户填写预设属性,只需要把遍历表头的逻辑替换为遍历allowedProperties列表即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:48:04