繁体   English   中英

清单中的项目不存在时掉落如何检查

[英]Falling over when item does not exist in list how to check

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

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来捆绑它,因为如果它不在列表中,请替换为空字符串,这可能是其他最好的捕获方法。

您可以改用.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); 
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM