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

C#如何识别列表中的不匹配值 修复时长校验始终返回匹配问题

问题定位

代码存在4个核心问题,导致逻辑完全不符合预期:

  1. 循环逻辑错误:遍历RangeValueList时每次都覆盖compareResult的值,最终compareResult只保留了和列表最后一个元素0:00:02,009的比较结果,完全没有判断是否匹配列表中任意一个元素。
  2. 分隔符不匹配:TimeSpan.ToString("g")默认使用英文句号.作为小数分隔符,输出格式为0:00:02.008,但RangeValueList里所有元素用的是逗号,作为小数分隔符,字符串完全不可能相等。
  3. 判断逻辑错误:String.Compare两个字符串相等时返回值为0,你错误判断等于1才算匹配,逻辑完全相反。
  4. 字符串比较校验时间范围不可靠:直接比较字符串很容易受区域文化、格式差异影响,校验时间范围应该直接比较TimeSpan类型值,不需要转字符串。

修正方案

最优方案(直接比较时间类型,避免格式问题)

TimeSpan temp_initial = TimeSpan.Parse(_InitialTonKopfPosition);
TimeSpan temp_current = TimeSpan.Parse(_CurrentTonKopfPosition);
TimeSpan result = temp_current.Subtract(temp_initial);
Report.Info("Data", string.Format("Audio is played for '{0}' seconds", result.ToString("g")));

// 直接定义时间范围,无需转字符串校验,可靠性更高
TimeSpan minDuration = TimeSpan.FromSeconds(1.997);
TimeSpan maxDuration = TimeSpan.FromSeconds(2.009);

if (result >= minDuration && result <= maxDuration)
{
    Report.Success("duration matched");
}
else
{
    Report.Failure("Not matched");
}

兼容原有列表匹配逻辑的修正方案

如果必须保留原有字符串列表的校验规则,可以按以下方式修改:

TimeSpan temp_initial = TimeSpan.Parse(_InitialTonKopfPosition);
TimeSpan temp_current = TimeSpan.Parse(_CurrentTonKopfPosition);
TimeSpan result = temp_current.Subtract(temp_initial);
// 转换为和列表格式一致的字符串,替换小数点为逗号
string output = result.ToString("g").Replace('.', ',');
Report.Info("Data", string.Format("Audio is played for '{0}' seconds", output));

List<string> RangeValueList = new List<string>
{
    "0:00:01,997", "0:00:01,998", "0:00:01,999",
    "0:00:02,000", "0:00:02,001", "0:00:02,002",
    "0:00:02,003", "0:00:02,004", "0:00:02,005",
    "0:00:02,006", "0:00:02,007", "0:00:02,008",
    "0:00:02,009"
};

// 直接判断列表是否包含目标字符串
bool isMatched = RangeValueList.Contains(output);
if (isMatched)
{
    Report.Success("duration matched");
}
else
{
    Report.Failure("Not matched");
}

内容的提问来源于stack exchange,提问作者Bilawal Wajid Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 13:36:09