对比字符串时间展示产品statusFinal值异常问题排查求助
问题排查:时段状态值显示异常
我尝试通过对比字符串时间值展示产品的statusFinal值,但出现异常:StartTimeNames中9:00至9:45时段的statusFinal值为空,10:00及之后时段可正常显示。
相关变量说明
_vmModel.keyValuePairs:ViewModel中的Dictionary对象_vmModel.ProductTypesSel:ProductType[]数组_vmModel.StartTimeNames:string[]数组
相关代码
Dictionary<int, List<KeyValuePair<string, string>>> keyValuePairs = _vmModel.keyValuePairs;
foreach (var item in _vmModel.ProductTypesSel) { List<KeyValuePair<string, string>> temp = keyValuePairs[item.Code]; for (int i = 0; i < _vmModel.StartTimeNames.Length; i++) { string filterStartTimeNames = _vmModel.StartTimeNames[i]; string statusFinal = ""; foreach (KeyValuePair<string, string> timeValue in temp) { if (filterStartTimeNames == timeValue.Key) { statusFinal = timeValue.Value; Console.WriteLine("LoopCheck Nested Locked Value: " + timeValue.Key); } else { Console.WriteLine("LoopCheck Nested Not Matched: " + timeValue.Key); } } Label statuslabel = new Label() { Text = statusFinal, WidthRequest = 80 }; } }
问题排查方向及修复建议
- 字符串匹配精度问题:检查
StartTimeNames中9:00-9:45的时间字符串,是否和keyValuePairs里的Key存在格式差异(比如前导零、空格、大小写,例如9:00vs09:00,或9:00末尾带空格)。代码使用==做严格字符串匹配,任何细微差异都会导致匹配失败。 - 循环逻辑优化:内层循环找到匹配项后未及时跳出,会继续遍历剩余项(虽不影响结果,但浪费性能),建议找到匹配后立即退出循环:
foreach (KeyValuePair<string, string> timeValue in temp) { if (filterStartTimeNames == timeValue.Key) { statusFinal = timeValue.Value; Console.WriteLine("LoopCheck Nested Locked Value: " + timeValue.Key); break; // 匹配成功后终止内层循环 } else { Console.WriteLine("LoopCheck Nested Not Matched: " + timeValue.Key); } } - 数据存在性验证:确认
keyValuePairs[item.Code]对应的列表中,是否真的包含9:00-9:45时段的Key。可在循环前打印temp的所有Key,检查是否缺失该时段数据。 - 安全取值避免异常:直接使用
keyValuePairs[item.Code]会在Key不存在时抛出异常,建议改用安全取值方式:if (keyValuePairs.TryGetValue(item.Code, out var temp)) { // 原有循环逻辑 } else { Console.WriteLine($"ProductType Code {item.Code} 无对应数据"); }
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

