2015-11-28 58 views
0

我正在处理一个小应用程序。当我添加新的目的地时,我想按照彼此最近的位置重新排列我的列表。按最近距离排序列表

使用CalcDistance方法我可以计算当前位置和下一个位置之间的距离。

但我坚持排序我的列表。任何想法?

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(); 
    } 

    } 
} 
+0

任何想法是什么?你不知道该怎么做? –

+0

详细说明*“我想通过彼此的最近位置重新排序我的列表”*。 –

+1

不可能。如果你有A,B,C,D点,其中距离A,B和C,D都是1单位和B,C是2单位。排序顺序应该是什么? –

回答

0

在你的情况,我完全建议SortedList类,但如果你一定要使用List,你可以从deliver点减去所有destination,然后排序。

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))); 

最后,sorted列表是你想要的。