2015-11-28 60 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列表是你想要的。