且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#列表中的最小差异

更新时间:2022-12-09 17:55:55

class Point
{
    public int X { get; set; }
    public int Y { get; set; }
    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<Point> differenceList =
            new List<Point>()
            {
                new Point(40, 60), 
                new Point(10, 20),
                new Point(20, 30), 
                new Point(12, 61) };

        var q = from p1 in differenceList
                from p2 in differenceList
                let distance = Math.Abs(p1.X - p2.X)
                where !object.ReferenceEquals(p1, p2)
                select new { Point1 = p1, Point2 = p2, Distance = distance };

        var minimum = q.OrderBy(r => r.Distance).First();
        Console.WriteLine(
            "X difference = " +
            minimum.Distance +
            " (which is " +
            Math.Max(minimum.Point1.X, minimum.Point2.X) +
            " - " +
            Math.Min(minimum.Point1.X, minimum.Point2.X) + ")");

        Console.ReadLine();
    }
}

您可以编写查询并在单个语句中选择最小值,如下所示:

You could write the query and selecting the minimum in a single statement like this:

var minimum = (from p1 in differenceList
                from p2 in differenceList
                let distance = Math.Abs(p1.X - p2.X)
                where !object.ReferenceEquals(p1, p2)
                orderby distance
                select new { Point1 = p1, Point2 = p2, Distance = distance }).First();

对y的查询几乎相同并且很简单

The query for y is nearly the same and trivial

编辑

包含重复项且正在使用System.Windows.Point的集合的解决方案:

Solution for a collection that contains duplicates and is using System.Windows.Point:

class Program
{
    static void Main(string[] args)
    {
        List<Point> differenceList =
            new List<Point>()
        {
            new Point(40, 60), 
            new Point(10, 20),
            new Point(20, 30), 
            new Point(12, 61),
            new Point(10, 20)};

        var q = from p1 in differenceList
                from p2 in differenceList
                let distance = Math.Abs(p1.X - p2.X)
                where !p1.Equals(p2)
                select new { Point1 = p1, Point2 = p2, Distance = distance };

        var minimum = q.OrderBy(r => r.Distance).First();
        Console.WriteLine(
            "X difference = " +
            minimum.Distance +
            " (which is " +
            Math.Max(minimum.Point1.X, minimum.Point2.X) +
            " - " +
            Math.Min(minimum.Point1.X, minimum.Point2.X) + ")");

        Console.ReadLine();
    }
}