lostiniceland
lostiniceland

Reputation: 3789

LINQ: grouping collection

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

Upvotes: 0

Views: 314

Answers (1)

Guffa
Guffa

Reputation: 700312

I see two problems with your query; you are sorting the groups instead of sorting the invaders, and you are using Take with 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:

var r =
    from invader in invaders
    orderby invader.Location.Y descending
    group invader by invader.Location.X into invaderGroup
    select invaderGroup;

Invader fire = r.Skip(random.Next(r.Count())).First().First();

Upvotes: 1

Related Questions