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

如何从Dictionary对象提取键值对并转换为List<KeyValue>?

将字典数据转换为List类型的解决方案

问题场景

你需要从secondDictionary(存储在Dictionary<string, object>的第二个元素值中)提取键值对,并转换为自定义的List<KeyValue>类型,其中KeyValue类定义如下:

public class KeyValue
{
    public string Key { get; set; }
    public object Value { get; set; }
}

实现代码

在原代码中获取secondDictionary后,添加以下逻辑完成转换:

public ActionResult _getprice([FromBody] JsonElement selectedOptionsJson)
{
    var selectedOptions = selectedOptionsJson; // 优化:无需重复反序列化JsonElement
    int ProductId = 0;
    var dictionaryOptions = new Dictionary<string, object>();
    foreach (var property in selectedOptions.EnumerateObject())
    {
        var propertyValue = GetObjectFromJsonElement(property.Value);
        dictionaryOptions[property.Name] = propertyValue;
        if (property.Name == "productId")
        {
            ProductId = Convert.ToInt32(propertyValue);
        }
    }     

    // 处理secondDictionary并转换为List<KeyValue>
    var secondDictionary = dictionaryOptions.ElementAtOrDefault(1).Value;
    List<KeyValue> keyValueList = new List<KeyValue>();
    
    // 类型校验确保安全转换
    if (secondDictionary is Dictionary<string, object> targetDictionary)
    {
        // 遍历字典,映射为KeyValue对象并收集到列表
        keyValueList = targetDictionary.Select(kv => new KeyValue
        {
            Key = kv.Key,
            Value = kv.Value
        }).ToList();
    }
    // 可选:处理非字典类型的异常情况
    else
    {
        return BadRequest("目标数据不是有效的字典结构");
    }

    return Json(keyValueList); // 返回转换后的列表,可按需调整
}

关键说明

  1. 类型安全转换:使用is运算符判断secondDictionary是否为Dictionary<string, object>,避免类型转换异常;
  2. LINQ映射:通过Select将字典的每个KeyValuePair<string, object>映射为自定义的KeyValue对象,再通过ToList()生成最终列表;
  3. 代码优化:原代码中重复反序列化JsonElement的操作可以省略,直接使用传入的selectedOptionsJson即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:16:08