i'm working on a little application. When i'm adding a new destination i want to reorder my list by the closest positions of each other.
With the CalcDistance method i can calculate the distance between the current position and next position.
But i'm stuck on sorting my list. Any idea?
public class Transportcar
{
public Destinations Start { get; set; }
public Destinations End { get; set; }
public int Deliveries { get; set; }
List<Destinations> _destinations;
public Transportcar()
{
_destinations = new List<Destinations>();
}
public void AddDestination(Destinations destination)
{
_destinations.Add(destination);
}
public IEnumerable<Destinations> Destinations {
get {
return _destinations.AsEnumerable();
}
}
public double CalcDistance(Destinations Start, Destinations End)
{
//een ouwe man zei ooit: c^2 = a^2 + b^2
return Math.Sqrt(Math.Pow(Math.Abs(Start.X - End.X), 2) + Math.Pow(Math.Abs(Start.Y - End.Y), 2));
}
}
public class Sendings
{
public List<Destinations> DestinationsTodo = new List<Destinations>();
public void SortList()
{
DestinationsTodo = DestinationsTodo.OrderBy(x => x.X).ThenBy(x => x.Y).ToList();
}
}
}
In your situation, i totally suggest the SortedList
class, but if you're sure to use the List
, you can subtract all destination
from deliver
point, and then sort it.
List<Point> sub = new List<Point>();
_destinations.ForEach(item => sub.Add(new Point(item.X - deliver.X, item.Y - deliver.Y)));
sub.Sort((a, b) =>
{
double d1 = Math.Pow(a.X, 2) + Math.Pow(a.Y, 2);
double d2 = Math.Pow(b.X, 2) + Math.Pow(b.Y, 2);
return d1.CompareTo(d2);
});
List<Point> sorted = new List<Point>();
sub.ForEach(item => sorted.Add(new Point(item.X + deliver.X, item.Y + deliver.Y)));
at the end, the sorted
list is what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.