为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
互换的青春 2023-08-20 14:55:01
我想创建一些 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,45,45,1现在我需要将每个值与 (1,1) 进行比较,但我不知道任何正确的数据结构,通过它我可以轻松存储我的列表并将每个值与 (1,1) 进行比较。请帮忙
查看完整描述

2 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

C# 7 有元组,我想您正在寻找它!


例如元组列表:


var positions = new List<(int x, int y)>

{

    (3,4),

    (5,4),

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



查看完整回答
反对 回复 2023-08-20
?
慕的地10843

TA贡献1785条经验 获得超8个赞

我假设这些点是平面上的点,我们可以使用毕达哥拉斯定理来获得两点之间的距离。

有了这个假设,我将创建一个新类来保存 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));

    }

}


查看完整回答
反对 回复 2023-08-20
  • 2 回答
  • 0 关注
  • 111 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信