[英]How to get 4 closest to “a” elements from the list of tuples in C#?
I have a list of tuples List<(double X, double Y)> Data
and a
variable of type double
.我有一个元组
List<(double X, double Y)> Data
和a
double
类型的变量。 It is required to add to the array (double, double)[] output
the 4 elements closest to a
.需要将最接近
a
4 个元素添加到数组(double, double)[] output
中。 They need to be found among all Data.X
.它们需要在所有
Data.X
中找到。 It is necessary to arrange data in order of distance from a
.有必要按照距离
a
的顺序排列数据。
Example:例子:
Input:输入:
a = 15.5;
{(-10, 1),
(12, 2),
(14, 3),
(16, 4),
(50, 5)}
Output: Output:
output [0] = (16, 4);
output [1] = (14, 3);
output [2] = (12, 2);
output [3] = (-10, 1);
EDIT:My current solution:编辑:我目前的解决方案:
class CubicSpline
{
List<(double X, double Y)> Data { get; set; }
public CubicSpline(List<(double X, double Y)> data)
{
Data = data;
}
/// <summary>
/// Method for finding 4 nearest neighbors for x.
/// </summary>
public (double, double)[] FindNeighbours(double x)
{
var temp = Data.OrderBy(b => Math.Abs(x - b.X)).ToList();
(double, double)[] output = new (double, double)[4];
for(int i = 0; i < 4; i++)
{
output[i] = temp[i];
}
return output;
}
}
Since you started with LINQ, you can use some other LINQ methods to compute the result:由于您从 LINQ 开始,您可以使用其他一些 LINQ 方法来计算结果:
public (double, double)[] FindNeighbours(double x) =>
Data.OrderBy(b => Math.Abs(x - b.X)).Take(4).ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.