猿问

在 C# 中创建 Pair 类型 (Value,Value) 的列表

我想创建一些 int 值的列表对,例如

(3,4), (5,4), (5,1)....(n,n)

然后将每个与单个目标匹配,例如

(1,1)

我需要将列表的每个值与目标(1,1)进行比较,以便它应该打印最接近(1,1)的点

预期结果。

(3,4)

最近的是什么

最近的意思是,假设我们有数字 4,5,6,7,8,我想找到最接近 12 的数字,那么答案将是 8,因为需要 4 才能到达 12,但 4+n 从其他数字移动到 12 ,所以与单个值不同,我有一对值 (n,n).... 并与 (n,n) 进行比较

我尝试过使用二维数组

positions = new int[3][,] 
{
    new int[,] { {3,4} },
    new int[,]{ {5,4}}, 
    new int[,] { {5,1} }

};

这给了我

3,4

5,4

5,1

现在我需要将每个值与 (1,1) 进行比较,但我不知道任何正确的数据结构,通过它我可以轻松存储我的列表并将每个值与 (1,1) 进行比较。

请帮忙


互换的青春
浏览 241回答 2
2回答

尚方宝剑之说

C# 7 有元组,我想您正在寻找它!例如元组列表:var positions = new List<(int x, int y)>{&nbsp; &nbsp; (3,4),&nbsp; &nbsp; (5,4),&nbsp; &nbsp; (5,1)};您可以找到“最近的”,例如如下所示:(int x, int y) value = (1, 1);var closest = positions.OrderBy(p => (p.x - value.x) + (p.y - value.y)).First(); // finds (5,1)

慕的地10843

我假设这些点是平面上的点,我们可以使用毕达哥拉斯定理来获得两点之间的距离。有了这个假设,我将创建一个新类来保存 x/y 位置数据和一个DistanceBetween运行Pythagorean theorem.static void Main(string[] args){    List<Point> points = new List<Point>    {        new Point(3, 4),        new Point(5, 4),        new Point(5, 1)    };    Point closestPoint = points.OrderBy(point => point.DistanceFromPoint(new Point(1, 1))).FirstOrDefault();    Console.WriteLine($"The closest point to 1,1 is {closestPoint.PosX},{closestPoint.PosY}");    Console.ReadLine();}private class Point{    public Point(int posX, int posY)    {        PosX = posX;        PosY = posY;    }    public int PosX { get; set; }    public int PosY { get; set; }    public double DistanceFromPoint(Point otherPoint)    {        return Math.Sqrt(Math.Pow((otherPoint.PosX - PosX), 2) + Math.Pow((otherPoint.PosY - PosY), 2));    }}
随时随地看视频慕课网APP
我要回答