【发布时间】:2022-01-15 03:03:22
【问题描述】:
我有一个包含多个连续数字的列表。我试图弄清楚如何知道相对于过去值的增加或减少的数量。例如
102, 201, 198, 200
即2增加(102, 201和198, 200)和1减少(201, 198)。这是一个很长的号码列表,所以手动很乏味。我是使用 C# 的初学者。
【问题讨论】:
-
你试过什么?能否请您展示您的尝试(代码)?
我有一个包含多个连续数字的列表。我试图弄清楚如何知道相对于过去值的增加或减少的数量。例如
102, 201, 198, 200
即2增加(102, 201和198, 200)和1减少(201, 198)。这是一个很长的号码列表,所以手动很乏味。我是使用 C# 的初学者。
【问题讨论】:
有很多方法,从 查询 在 Linq 的帮助下:
using System.Linq;
...
int[] source = new int[] { 102, 201, 198, 200 };
...
// Probably, the most generic approach
var result = source.Aggregate(
(Inc: 0, Dec: 0, prior: (int?)null),
(s, a) => (s.Inc + (s.prior < a ? 1 : 0), s.Dec + (s.prior > a ? 1 : 0), a));
Console.Write($"Increasing: {result.Inc}; decreasing: {result.Dec}");
直到老for循环:
int Inc = 0;
int Dec = 0;
// Probably, the easiest to understand solution
for (int i = 1; i < source.Length; ++i)
if (source[i - 1] > source[i])
Dec += 1;
else if (source[i - 1] < source[i])
Inc += 1;
Console.Write($"Increasing: {Inc}; decreasing: {Dec}");
编辑: Linq Aggregate 解释。
Aggregate(
(Inc: 0, Dec: 0, prior: (int?)null),
(s, a) => (s.Inc + (s.prior < a ? 1 : 0), s.Dec + (s.prior > a ? 1 : 0), a));
为了从游标中获取单个值,我们使用Aggregate。
第一个参数
(Inc: 0, Dec: 0, prior: (int?)null)
是初始值(命名元组,用于在一个实例中组合多个属性)。这里我们有 0 增加和减少,null 用于上一项。
第二个参数
(s, a) => (s.Inc + (s.prior < a ? 1 : 0), s.Dec + (s.prior > a ? 1 : 0), a)
规则是如何将下一个项目a 添加到聚合项目s。我们应该
prior项目小于当前a的情况下增加s.Inc:s.Inc + (s.prior < a ? 1 : 0)
prior 项目大于当前a,则增加s.Dec:s.Dec + (s.prior > a ? 1 : 0)
a 分配为下一个prior 元素。让我们稍微罗嗦,但我希望更具可读性:
.Aggregate(
(Inc: 0, // no increasing
Dec: 0, // no decreasing
prior: (int?)null // no prior item
),
(s, a) => ( // s - partial aggregation, a - to add item
Inc: s.Inc + (s.prior < a ? 1 : 0), // Increment Inc if required
Dec: s.Dec + (s.prior > a ? 1 : 0), // Increment Dec if required
prior: a // Set a as a prior
)
)
希望,现在更清楚 Aggregate 的幕后情况了
【讨论】:
Aggregate 解释
int[] source = new int[] { 102, 201, 198, 200 };
int Increment = 0;
int Decrement= 0;
int k;
for (k=1; k< array.length; k++)
if (array[k - 1] > array[k])
Decrement++;
else
{
if (array[k - 1] < array[k])
Increment++;
}
Console.Write("Increasing: {Increment}, decreasing: {Decrement}");
}
【讨论】:
在这种情况下,您可以使用for loop:
for (int i = 0; i < listOfNumbers.Length; i++)
{
int currentEntry = listOfNumbers [i];
if(i > 0){
int previousEntry = listOfNumbers [i - 1];
Console.Log("Change from previous : " + (currentEntry-previousEntry));
}else{
Console.Log("No previous entry so no change can be found.");
}
}
【讨论】: