当列表中不存在项目如何检查时,会发生故障

时间:2018-06-18 15:37:22

标签: c# linq

我有这个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)  

但实际上这个项目的代码是失败的我不能使用count来绑定它,因为它可能有其他代码保留它是什么是我最好的陷阱方式,如果它不在列表中替换为空字符串而不是。 / p>

2 个答案:

答案 0 :(得分:2)

您可以使用.FirstOrDefault()代替,然后在继续之前检查结果是否为null。你所写的问题是.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;
}

事实上,如果sportgender的所有内容都可以为空(我不知道在此代码运行之前它们设置了什么或者你对它们有什么规则) ),你可以这样做:

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); 
}

答案 1 :(得分:1)

使用FirstOrDefault代替First。当谓词与任何元素都不匹配时,First会抛出异常(Sequence不包含匹配元素)。

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);
    }
}