C#用Find查询JSON反序列化列表时报string转bool隐式转换错误
报错原因
List<T>.Find() 方法要求传入的参数是返回bool类型的谓词委托,你在嵌套使用Find时,外层Find的委托最终返回了字符串类型的mp属性值,而非布尔值,因此触发了类型转换报错。你大概率写了类似如下的错误代码:
// 错误示例 var targetMp = rootMedicationMappingList.Find(r => r.TpuuItems.Find(t => t.TpuuValue == "000000002").Mp );
修复实现
假设你使用的类结构如下:
// 反序列化对应类结构 public class RootMedicationMapping { public List<TpuuMappingItem> TpuuItems { get; set; } } public class TpuuMappingItem { public string TpuuValue { get; set; } public string Mp { get; set; } }
方案1:嵌套Find实现
public string GetMpByTpuu(List<RootMedicationMapping> mappingList, string targetTpuu) { // 先判断根条目下是否存在匹配的tpuu项,返回布尔值符合Find要求 var matchedRoot = mappingList.Find(root => root.TpuuItems != null && root.TpuuItems.Exists(item => item.TpuuValue == targetTpuu) ); // 无匹配根条目返回默认值 if (matchedRoot == null) return null; // 从匹配的根条目下取出对应mp值 var matchedItem = matchedRoot.TpuuItems.Find(item => item.TpuuValue == targetTpuu); return matchedItem?.Mp; }
方案2:LINQ展平查询(更简洁高效)
引入System.Linq命名空间后,直接展平嵌套列表查询,无需分层查找:
using System.Linq; public string GetMpByTpuu(List<RootMedicationMapping> mappingList, string targetTpuu) { return mappingList // 过滤嵌套列表为空的根条目,避免空引用异常 .Where(root => root.TpuuItems != null) // 把所有嵌套的tpuu项展平为一维列表 .SelectMany(root => root.TpuuItems) // 匹配第一个符合条件的项,无匹配返回null .FirstOrDefault(item => item.TpuuValue == targetTpuu) // 返回对应的mp值 ?.Mp; }
注意事项
- 如果需要忽略tpuu字符串的大小写匹配,可以将判断条件替换为
item.TpuuValue.Equals(targetTpuu, StringComparison.OrdinalIgnoreCase) - 如果需要查询所有匹配tpuu的mp值,将
FirstOrDefault替换为Where,遍历返回结果集即可 - 如果反序列化后根条目可能为null,可在最前面加空判断过滤
内容的提问来源于stack exchange,提问作者Budd
相关产品推荐
相关产品推荐

