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

C# LINQ如何从DemoResponse的Errors集合中提取指定匹配的错误码

问题根因

原来的代码取值时未过滤匹配Codes的错误条目,直接取了Errors集合第一条的StackTrace值,所以只有当目标错误码在集合首位时才能正确取值。

修复方案

方案1:在原有代码基础上修改

仅修改if块内的取值逻辑,先过滤再取值即可:

public void method()
{
    var displayCodes = Codes.Split(',');
    DemoResponse response = webService.GetResponse();  //从API获取响应

    if(response.Errors.Any(x => displayCodes.Contains(x.StackTrace)))
    {
        // 先过滤匹配的错误,再取对应的StackTrace
        int myCode = int.Parse(response.Errors.First(x => displayCodes.Contains(x.StackTrace)).StackTrace);
    }
}

方案2:优化遍历次数(推荐)

原有代码中Any判断和后续取值会遍历两次Errors集合,可合并为一次遍历降低性能开销:

public void method()
{
    var displayCodes = Codes.Split(',');
    DemoResponse response = webService.GetResponse();  //从API获取响应

    // 一次遍历直接找到匹配的错误条目
    var matchedError = response.Errors.FirstOrDefault(x => displayCodes.Contains(x.StackTrace));
    if (matchedError != null)
    {
        int myCode = int.Parse(matchedError.StackTrace);
    }
}

根据API返回规则,Errors集合必定存在一个匹配的错误码,也可以直接用First省略空判断:

int myCode = int.Parse(response.Errors.First(x => displayCodes.Contains(x.StackTrace)).StackTrace);

内容的提问来源于stack exchange,提问作者DevP

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:06:03