C#错误 - "并非所有代码路径都返回值"

Ler*_*ica 2 c#

这是一种相当简单的方法.我entity framework用来获取一些数据,然后检查一些值if statement.但是现在该方法标有红色.

这是我的方法:

private bool IsSoleInProduction(long? shoeLastID)
{
    if (shoeLastID == null)
    {
        MessageBox.Show(Resources.ERROR_SAVE, 
                        "Error", 
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Error);
        return false;
    }

    ISoleService soleService = 
        UnityDependencyResolver.Instance.GetService<ISoleService>();

    List<Sole> entity = 
        soleService.All().Where(s => s.ShoeLastID == shoeLastID).ToList();

    if (entity.Count() != 0)
    {
        foreach (var items in entity)
        {
            if (items.Status == 20)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    else
    {
        return false;
    }    
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

cuo*_*gle 7

你需要利用带有An y 的LINQ ,替换你的代码:

if (entity.Count() != 0)
{
    foreach (var items in entity)
    {
        if (items.Status == 20)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
else
{
    return false;
}    
Run Code Online (Sandbox Code Playgroud)

更简单的代码:

 return entity.Any(item => item.Status == 20);
Run Code Online (Sandbox Code Playgroud)

甚至更好的表现:

 return soleService.All()
              .Any(s => s.ShoeLastID == shoeLastID
                     && s.Status == 20); 
Run Code Online (Sandbox Code Playgroud)

编辑:随着您的评论,下面的代码是您所需要的:

  List<Sole> entity =  soleService.All()
                            .FirstOrDefault(s => s.ShoeLastID == shoeLastID);

  return entity == null ? false : entity.Status == 20;
Run Code Online (Sandbox Code Playgroud)