C#列表中的最小差异

编程入门 行业动态 更新时间:2024-10-10 16:19:53
本文介绍了C#列表中的最小差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在xy点数据列表中找到最小的差异. (可以包含重复的x值和y值)

I want to find minimum difference in a list of xy point data. (can contain duplicate x values and y values)

Example: List<Point> differenceList = new List<Point>() { (10,0), (10,20), (20,30), (12,61) };

预期结果

X difference = 2 Y difference = 20

是否可以使用linq/lambda表达式优雅地做到这一点? 谢谢!

is it possible to do this elegantly may be using linq/lambda expressions? Thanks!

推荐答案

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

更多推荐

C#列表中的最小差异

本文发布于:2023-11-29 06:21:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645593.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最小   差异   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!