我有一个循环,我得到我的价值
var val= (from entry in Data select (entry.Value)).ToList().First();
数据是Dictionary
,我暂时使用,val
是double类型。
所以我有
foreach(var v in val)
if(v > 100){
// here I wanna check if the difference between current and last value is greaterthan 10, to skip the setValue and exit the foreach loop.
a.setValue(v);
}
现在,如果当前和之前的差异大于10,我不想设置该值。
我应该创建一个列表还是什么?
答案 0 :(得分:1)
decimal previousVal = 0;
foreach(var v in val)
{
if(previousVal > 0)
{
if(Math.Abs(v - previousVal) > 10)
{
// diff greater than 10
}
}
a.setValue(v);
previousVal = v;
}
编辑:
0
只是表明这是否是循环的第一次迭代。如果0
是潜在值,则可以使用可为空的小数:
decimal ? previousVal = null;
foreach(var v in val)
{
if(previousVal != null)
{
if(Math.Abs(v - previousVal) > 10)
{
// diff greater than 10
}
}
a.setValue(v);
previousVal = v;
}
答案 1 :(得分:0)
类似于Enumerable.Zip您要找的东西吗?
var numbers = new []{ 1, 2, 3, 40, 41 };
var differences = numbers.Skip(1).Zip(numbers, (prev, curr) => Math.Abs(prev - curr));
var result = numbers.TakeWhile((obj, index) => index == 0 || numbers[index - 1] <= 10);
// outputs:
// 1
// 2
// 3
// 40
答案 2 :(得分:0)
如果我理解你的情况,请考虑尝试:
//List<double>
var list = (from entry in Data select (entry.Value)).ToList();
double previousValue = 0;
for (int i=0; i< list.Count; i++)
{
var diff = list[i] - previousValue;
if (diff <= 10)
a.setValue(list[i]);
previousValue = list[i];
}