I got a C# class:
public class Agent
{
public string AgentId { set; get; }
public double Longitude { set; get; }
public double Latitude { set; get; }
}
There are several agents in several different locations. During the program's lifetime, they can receive a call to another (latitude, longitude) point which is unknown during runtime. I got an API to calculate the distance in meters between their location and the given point. What I need eventually is to find the 5 closest agents to the given point.
What I did in order to achieve this is adding another class:
public class AgentDistance : Agent, IComparable<AgentDistance>
{
public AgentDistance(Agent agent)
{
if(agent == null)
{
throw new Exception("Can't initalize agent with distance since agent is null");
}
this.AgentId = agent.AgentId;
this.Latitude = agent.Latitude;
this.Longitude = agent.Longitude;
}
public double Distance { set; get; }
public int CompareTo(AgentDistance other)
{
if(other == null)
{
return 1;
}
return Distance.CompareTo(other.Distance);
}
}
And the usage:
var agents = db.GetAgents();
if(agents == null || agents.Count == 0)
{
Console.WriteLine("No Results");
}
List<AgentDistance> agentsWithDistance = new List<AgentDistance>();
foreach(Agent agent in agents)
{
double res = ws.GetDistanceMeters(agent.Latitude, agent.Longitude, customerLatitude, customerLongitude);
agentsWithDistance.Add(new AgentDistance(agent) { Distance = res });
}
agentsWithDistance.Sort();
for(int i = 0; i < 5; i++)
{
Console.WriteLine(string.Format("agent_id: {0} distance: {1} m", agentsWithDistance[i].AgentId, agentsWithDistance[i].Distance));
}
It works, but is there a more elegant way to do it? I'm not sure if adding another class might be a bit redundant since all it does is just adding a property for sorting, but adding the distance property to the Agent
class, doesn't make so much sense.