What I would like is to loop through each item of a List in ascending order of distance (so the nearest targets are used first).
foreach (ShipCompartment enemyComp in enemy.ListOfCompartments.OrderBy(...))
The problem is that the distance is not a member of the class. Therefore I can't use:
foreach (ShipCompartment enemyComp in enemy.ListOfCompartments
.OrderBy(c => c.Distance))
The code used to calculate distance is:
// Get distance between player and enemy compartments
float distanceToTarget = Vector2.Distance(playerComp.Position,
enemyComp.Position);
How can I incorporate the calculation into OrderBy()? I've looked over here but it only returns the nearest Vector2.
Many thanks for your assistance.
The simple option would be to move the function call to the OrderBy call, so something like:
foreach (ShipCompartment enemyComp in enemy.ListOfCompartments.OrderBy(c => Vector2.Distance(playerComp.Position, c.Position)))
Your best solution if you need Distance generally (and not only for sorting) is to use Select to create a new structure that contains a definition of Distance and then use OrderBy. For example:
For the data structure:
class Coordinates
{
public int Value { get; set; }
public float Longitude { get; set; }
public float Latitude { get; set; }
}
You call it like this:
foreach(var coordinate in coordinates.Select(x=> new
{
Value = x.Value,
Longitude = x.Longitude,
Latitude = x.Latitude,
Distance = x.Longitude + x.Latitude
}).OrderBy(x=>x.Distance))
Process(coordinate);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With