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

C#中如何将特定键格式的Dictionary<string,string>解析为自定义对象

解决方案

你只需要把字典的Key按规则拆分出索引值和属性名,按索引分组之后把对应的Value映射到对象属性上即可,以下是可直接运行的C#实现:


步骤1:定义目标实体类

public class DataItem
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string Description { get; set; }
}

步骤2:编写解析逻辑

代码兼容你给出的Key格式(包括description后缺右括号的特殊情况):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

// 你的原始输入字典
Dictionary<string, string> rawDict = new Dictionary<string, string>
{
    {"data[0][name]", "Test"},
    {"data[0][type]", "Type Test"},
    {"data[0][description", "Description Test"},
    {"data[1][name]", "Test"},
    {"data[1][type]", "Type Test"},
    {"data[1][description", "Description Test"},
    {"data[2][name]", "Test"},
    {"data[2][type]", "Type Test"},
    {"data[2][description", "Description Test"}
};

// 正则匹配提取索引和属性名
Regex keyRegex = new Regex(@"data\[(\d+)\]\[(\w+)");
List<DataItem> result = rawDict
    .Select(kv => 
    {
        var match = keyRegex.Match(kv.Key);
        if (!match.Success) return null;
        int index = int.Parse(match.Groups[1].Value);
        string propName = match.Groups[2].Value.ToLower();
        return new { Index = index, PropName = propName, kv.Value };
    })
    .Where(x => x != null)
    .GroupBy(x => x.Index)
    .Select(g => new DataItem
    {
        Name = g.FirstOrDefault(x => x.PropName == "name")?.Value,
        Type = g.FirstOrDefault(x => x.PropName == "type")?.Value,
        Description = g.FirstOrDefault(x => x.PropName == "description")?.Value
    })
    .ToList();

如果你不想引入正则依赖,也可以把Key解析部分替换为字符串拆分操作,整体分组映射的逻辑完全一致。


结果说明

  • 最终得到的result是包含3个DataItem对象的集合
  • 每个对象的Name/Type/Description属性完全匹配字典中的对应取值
  • 即使部分索引下缺少某个属性,也只会返回null不会触发运行时错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:54:08