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

如何将ICollection<object>转换为字符串数组?代码返回空列表

问题分析与解决方案

问题描述

给变量添加监视后,其内部结构显示result是包含单个字典元素的集合,字典中键"items"对应的值为字符串数组["item1", "item2", "item3"]。我希望提取出这个字符串数组,但以下代码返回空列表,无法定位问题:

List<string> itemsInReslt = new List<string>();
foreach (IDictionary<string, object> r in result)
{
    foreach (object value in r.Values)
    {
        itemsInReslt.Add(value.ToString());
    }
}

问题原因

  1. 原代码直接将字典值调用ToString()添加到列表,但字典中"items"对应的值是字符串数组对象,ToString()只会返回类型标识(如System.String[]),而非数组内的元素;
  2. 若返回空列表,大概率是result未正确枚举,或字典中不存在"items"键,或值的类型不匹配,导致没有有效元素被添加。

修正实现

基础遍历版

List<string> itemsInResult = new List<string>();
foreach (IDictionary<string, object> r in result)
{
    // 安全获取"items"对应的值,并判断是否为字符串数组
    if (r.TryGetValue("items", out object value) && value is string[] itemsArray)
    {
        itemsInResult.AddRange(itemsArray);
    }
}
// 如需转为数组,执行以下代码
// string[] finalItems = itemsInResult.ToArray();

LINQ简化版(更优)

using System.Linq;

string[] finalItems = result
    .SelectMany(dict => 
        dict.TryGetValue("items", out object val) && val is string[] arr 
            ? arr 
            : Enumerable.Empty<string>()
    )
    .ToArray();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:15:14