I am programming space invaders for practise 😉 and works quite well but I have a problem with my invaders returning fire.
All invaders are stored in a list and I use linq to group those invaders by their X-location so I can access a group randomly and take the invader that is at the bottom of that column to shoot back.
var r = from invader in invaders
group invader by invader.Location.X into invaderGroup
orderby invaderGroup descending
select invaderGroup.Take(random.Next(0, invaderGroup.Count()));
But whatever I try (e.g. select new { invaderGroup.Key, invadergroup }; ) my result is always null?
Can anybody provide me with some help/hint? Thanks
I see two problems with your query; you are sorting the groups instead of sorting the invaders, and you are using
Takewith a random number that can be zero, so that it may return an empty result.This works for grouping the invaders by X coordinate, sorting them by Y coordinate, picking a group by random and getting the invader with the highest Y coordinate: