【问题标题】:Sort list by closest distances按最近距离排序列表
【发布时间】:2015-11-28 21:46:41
【问题描述】:

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

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

    }
}

【问题讨论】:

  • 知道什么吗?你到底不知道怎么做?
  • 详细说明“我想按彼此最近的位置重新排列我的列表”
  • 不可能。如果您有点 A、B、C、D,其中距离 A、B 和 C、D 都是 1 个单位,而 B、C 是 2 个单位。排序顺序应该是什么?
  • 首先使用支持此类事物(地理)的数据类型。
  • 您也可以在 Google 上搜索“旅行推销员问题”(TSP - simple.wikipedia.org/wiki/Travelling_salesman_problem),这将引导您讨论如何解决此类问题。

标签: c# linq sorting


【解决方案1】:

在您的情况下,我完全建议使用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 列表就是你想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2012-05-30
    • 2014-06-26
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多