InvalidOperationException(不包含任何元素的序列)

时间:2011-04-17 09:56:41

标签: c# winforms invalidoperationexception

            List<Invaders> invadersShooting = new List<Invaders>();
        Invaders invaderA=new Invaders();
    try
            {
        var invaderByLocationX = from invadersSortByLocation in invaders
                                 group invadersSortByLocation by invadersSortByLocation.Location.Y
                                 into invaderGroup
                                 orderby invaderGroup.Key
                                 select invaderGroup;

        if (invaderByLocationX != null)
        {

                invadersShooting = invaderByLocationX.Last().ToList();// it is being throwing constantly here.. How can i prevent it from being thrown

                invaderA = invadersShooting[r.Next(0, invadersShooting.Count)];




                if (r.Next(5) < 4 - randomShot)
                {
                    Invadershots.Add(new Shot(invaderA.Location, Direction.DOWN, gameBoundaries, WEAPON.DEFAULT, isWeapon));
                }
        }
            }
    catch (Exception e)
    { }
    }

如何防止错误发生?如何让程序检查invaderByLocationX是否为空?因为它是空的,因此抛出异常:(

1 个答案:

答案 0 :(得分:2)

您可以使用LastOrDefault,如果序列为空,它将返回null。然后,您需要检查是否为空。

var invader = invaderByLocationX.LastOrDefault();
if(invader == null)
{
    // do something
}
else
{
    invaderA = invadersShooting[r.Next(0, invadersShooting.Count)];
    // etc
}

另请注意,invaderByLocationX永远不能为null,因此无效的空检查。