如何将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()); } }
问题原因
- 原代码直接将字典值调用
ToString()添加到列表,但字典中"items"对应的值是字符串数组对象,ToString()只会返回类型标识(如System.String[]),而非数组内的元素; - 若返回空列表,大概率是
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
相关产品推荐
相关产品推荐

