Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

InvalidOperationException (sequence containing no elements

            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 :(

Upvotes: 1

Views: 1045

Answers (1)

Talljoe
Talljoe

Reputation: 14827

You can use LastOrDefault which will return null if the sequence is empty. You'll then want to check for null.

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

Also note that invaderByLocationX can never be null, so the null check in unecessary.

Upvotes: 2

Related Questions