linq 将lambda表达式重构为sonar,在至少一个执行路径上显示为null

jgovgodb  于 2023-09-28  发布在  其他
关注(0)|答案(1)|浏览(76)

我想将此代码重构为Sonarqube,显示为**'bidRelations。其中(x => x.Type == _appSettings.ResType).FirstOrDefault()'在至少一个执行路径上为null。**

public new List<CustomerModel> BuildRelationLines(PH.ParserHubApiBidResponse vendorBid)
    {
        
        List<CustomerModel> bidRelations = base.BuildRelationLines(vendorBid);
       
        if (bidRelations != null && !string.IsNullOrEmpty(vendorBid.Custom2) && !string.IsNullOrEmpty(_appSettings.ResType))
        {
            bidRelations.Where(x => x.Type == _appSettings.ResType).FirstOrDefault().CustInternalId = vendorBid.Custom2.Replace("-", ""); 
        }
        return bidRelations; 
    }

Tia

mv1qrgav

mv1qrgav1#

这是因为FirstOrDefault可能返回null。在访问CustInternalId属性之前,您应该检查它是否为null

public new List<CustomerModel> BuildRelationLines(PH.ParserHubApiBidResponse vendorBid)
{
    List<CustomerModel> bidRelations = base.BuildRelationLines(vendorBid);
    
    if (bidRelations != null && !string.IsNullOrEmpty(vendorBid.Custom2) && !string.IsNullOrEmpty(_appSettings.ResType))
    {
        var relation = bidRelations.FirstOrDefault(x => x.Type == _appSettings.ResType);
        if (relation != null)
            relation.CustInternalId = vendorBid.Custom2.Replace("-", ""); 
    }
    return bidRelations; 
}

相关问题