代码之家  ›  专栏  ›  技术社区  ›  David B

列表中不存在项目时摔倒如何检查

  •  0
  • David B  · 技术社区  · 7 年前

    我有这个linq查询,但是当没有设置用户的性别时,它就会崩溃,它说的是squencce

    List<StandardLookUpList> _AnalsisCodes = GetAnayalsisCodesForExportCode();
    
    var codesForThisItem = _AnalsisCodes.Where(w => w.ItemCode == item.ItemCode);
    if (codesForThisItem.Count()  > 0 )
    {
         if (codesForThisItem.First(x => x.code == Constants.Sport) != null)
          sport = codesForThisItem.First(x => x.code == Constants.Sport);
    
           if(codesForThisItem.First(x => x.code == Constants.Gender) !=null)
           gender = codesForThisItem.First(x => x.code == Constants.Gender);
    }     
    

    我以为这条线足以解决这个问题?。

    if (codesForThisItem.First(x => x.code == Constants.Sport)  
    

    但它实际上是这个项目的代码是失败的,我不能使用计数带,因为它可能有其他代码举行对它什么是我最好的方式捕获,如果它不在列表替换为空字符串。

    2 回复  |  直到 7 年前
        1
  •  2
  •   ADyson    7 年前

    你可以用 .FirstOrDefault() 而是,然后在继续之前检查结果是否为空。你写的问题是 .First() 总是希望有一个匹配的结果:

    List<StandardLookUpList> _AnalsisCodes = GetAnayalsisCodesForExportCode();
    var codesForThisItem = _AnalsisCodes.Where(w => w.ItemCode == item.ItemCode);
    
    if (codesForThisItem.Any())
    {
         var sportResult = codesForThisItem.FirstOrDefault(x => x.code == Constants.Sport);
         if (sportResult != null) sport = sportResult;
    
         var genderResult = codesForThisItem.FirstOrDefault(x => x.code == Constants.Gender); 
         if (genderResult != null) gender = genderResult;
    }
    

    事实上,如果对你来说 sport gender 它们可能是空的(我不知道在代码运行之前它们被设置了什么,或者您对它们有什么规则),您可以只执行以下操作:

    List<StandardLookUpList> _AnalsisCodes = GetAnayalsisCodesForExportCode();
    var codesForThisItem = _AnalsisCodes.Where(w => w.ItemCode == item.ItemCode);
    
    if (codesForThisItem.Any())
    {
         sport = codesForThisItem.FirstOrDefault(x => x.code == Constants.Sport);
         gender = codesForThisItem.FirstOrDefault(x => x.code == Constants.Gender); 
    }
    
        2
  •  1
  •   Scott    7 年前

    使用 FirstOrDefault 而不是 First . 当谓词不匹配任何元素时,First将引发异常(序列不包含匹配的元素)。

    List<StandardLookUpList > _AnalsisCodes = GetAnayalsisCodesForExportCode();
    
    var codesForThisItem = _AnalsisCodes.Where(w => w.ItemCode == item.ItemCode);
    if (codesForThisItem.Any())
    {
        if (codesForThisItem.FirstOrDefault(x => x.code == Constants.Sport) != null)
        {
            sport = codesForThisItem.First(x => x.code == Constants.Sport);
        }
    
        if (codesForThisItem.FirstOrDefault(x => x.code == Constants.Gender) != null)
        {
            gender = codesForThisItem.First(x => x.code == Constants.Gender);
        }
    }