[英]How to get 4 closest to “a” elements from the list of tuples in C#?
我有一个元组List<(double X, double Y)> Data
和a
double
类型的变量。 需要将最接近a
4 个元素添加到数组(double, double)[] output
中。 它们需要在所有Data.X
中找到。 有必要按照距离a
的顺序排列数据。
例子:
输入:
a = 15.5;
{(-10, 1),
(12, 2),
(14, 3),
(16, 4),
(50, 5)}
Output:
output [0] = (16, 4);
output [1] = (14, 3);
output [2] = (12, 2);
output [3] = (-10, 1);
编辑:我目前的解决方案:
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;
}
}
由于您从 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.