从FireStore获取集合文档时数组显示System.Collections.Generic.List`1[System.String]的解决办法
解决Firestore数组字段显示为
System.Collections.Generic.List1[System.String]`的问题 在检索FireStore中名为siparisler的集合文档时,数组字段无法正常展示具体元素,而是输出System.Collections.Generic.List1[System.String]`,原代码如下:
async void getData() { listBox1.Items.Clear(); Query allCitiesQuery = database.Collection("siparisler"); QuerySnapshot allCitiesQuerySnapshot = await allCitiesQuery.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in allCitiesQuerySnapshot.Documents) { listBox1.Items.Add("_________________________________________"); Dictionary<string, object> city = documentSnapshot.ToDictionary(); foreach (var pair in city) { listBox1.Items.Add(pair.Key + ": " + pair.Value); } } }
解决方案
问题根源是当pair.Value为List<string>类型时,直接拼接字符串会调用其默认的ToString()方法,返回类型名称而非元素内容。需添加类型判断,将数组元素拼接为可读字符串。
修改后的代码:
async void getData() { listBox1.Items.Clear(); Query allCitiesQuery = database.Collection("siparisler"); QuerySnapshot allCitiesQuerySnapshot = await allCitiesQuery.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in allCitiesQuerySnapshot.Documents) { listBox1.Items.Add("_________________________________________"); Dictionary<string, object> city = documentSnapshot.ToDictionary(); foreach (var pair in city) { // 判断值是否为字符串列表 if (pair.Value is List<string> stringList) { // 将列表元素用逗号拼接成字符串 string listContent = string.Join(", ", stringList); listBox1.Items.Add($"{pair.Key}: [{listContent}]"); } else { // 非数组类型直接输出 listBox1.Items.Add($"{pair.Key}: {pair.Value}"); } } } }
- 通过
is关键字判断pair.Value是否为List<string>类型,同时完成类型转换 - 使用
string.Join将数组元素拼接成以逗号分隔的字符串,并用方括号包裹,提升可读性 - 非数组类型保持原有输出逻辑
内容的提问来源于stack exchange,提问作者the litch
相关产品推荐
相关产品推荐

