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)
{ }
}
我怎样才能防止错误的发生?我怎样才能让程序检查入侵者ByLocationX 是否为空?因为它是空的,因此抛出异常:(
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)
{ }
}
How can i prevent the error from happening? how can i make the program check that invaderByLocationX is empty? cause it is empty, therefore the exception is thrown :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
LastOrDefault
如果序列为空,它将返回 null。然后你需要检查是否为空。另请注意,invaderByLocationX 永远不能为空,因此空检查是不必要的。
You can use
LastOrDefault
which will return null if the sequence is empty. You'll then want to check for null.Also note that invaderByLocationX can never be null, so the null check in unecessary.