我的目标是在数组或列表中找到数字对。在这种情况下,一对由两个条目之间的最大差异定义。例如
1
50
2
100
102
800
对(如果最大差异阈值为 2)与行号(数组号):
1,2 line number of 1 is 0
100,101 line number of 100 is 3
我该怎么做?
最佳答案
您可以使用 LINQ 来执行此操作:
var numbers = new[]
{
1,
50,
2,
100,
102,
800
};
var treshold = 2;
var numWithIndexes = numbers.Select((value, index) => new { value, index });
var pairs = from num1 in numWithIndexes
from num2 in numWithIndexes
where (num2.value - num1.value <= treshold) && (num2.value - num1.value > 0)
select new[]
{
num1.value, // first number in the pair
num2.value, // second number in the pair
num1.index, // index of the first number in the pair
num2.index // index of the second member in the pair
};
foreach (var pair in pairs)
{
Console.WriteLine("Pair found: " + pair[0] + ", " + pair[1] +
" at line " + pair[2] + ", " + pair[3]);
}
关于c# - 在数组或列表中查找数字对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32287037/