c# - 在数组或列表中查找数字对

标签 c# arrays

我的目标是在数组或列表中找到数字对。在这种情况下,一对由两个条目之间的最大差异定义。例如

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/

相关文章:

c# - 混淆硬编码的许可证 key

c# - WPF:如何使用 MVVM 将命令绑定(bind)到 ListBoxItem?

Java:从 block 中的数组列表创建数组的有效方法

c++ - 为什么我们在传递给 C++ 中的函数时将数组大小指定为参数?

c# - 在c#中保存一个excel文件

c# - 如何从组合框中删除更多项目?

ios - Swift Array 将 nil 的 var 传递给 .contains 和 .filter 时会发生什么

c - 在 C 中查找字符串数组中的唯一元素

c - 如何使用 c 将数组作为指针传递给函数来排序?

c# - 像在 WPF 中一样在 winform 中绑定(bind)