我正在使用ForEach statement
为属性值分配属性值。输出看起来像这样......
Startingpoint | length
-----------------------
0 | 1
1 | 54.47
55.47 | 47.98
所以长度计算如此......
length = *next item starting point - current item starting point
这是我想在Pseudo Code esque中查看的内容。
foreach (DefectMap obj in dm)
{
mdmList.Add(new ModifiedDefectMap()
{
StartingPoint = obj.Start,
Length = ValueOfNext().obj.Start - obj.Start
问题是,我无法告诉"ValueOfNext().obj.Start"
会是什么,因为我正处于foreach
循环的当前Itereation。
答案 0 :(得分:3)
使用常规for循环
//Count-1 to stop at the second to last item
for(int i = 0; i < dm.Count-1; ++i)
{
mdmList.Add(new ModifiedDefectMap()
{
StartingPoint = dm[i].Start,
Length = dm[i+1].Start - dm[i].Start
});
}
答案 1 :(得分:3)
您可以尝试.Zip()
声明。
mdmList = dm.Zip(dm.Skip(1), (current, next) => new ModifiedDefectMap
{
StartingPoint = current.Start,
Length = next.Start - current.Start
});
跳过偏移列表,因此您最终将所有相邻元素对映射到current
和next
,然后使用它们创建对象。看起来很干净。
答案 2 :(得分:1)
如果您想一次访问多个项目,最好使用for
循环。
for(int i = 0; i < dm.Count-1; ++i)
{
mdmList.Add(new ModifiedDefectMap()
{
StartingPoint = dm[i].Start,
Length = dm[i+1].Start - dm[i].Start
}
}
如果您仍想使用foreach
循环,可以使用IndexOf
答案 3 :(得分:1)
我不是特别确定你是否可以查看foreach
中的下一个值,但是,如果你正在进行这样的实现,我建议使用for循环来提供下一个值,那么一定要确定检查be-next next值是否在数组的范围内。
for(int i = 0; i < list.Length; i++)
{
list[i] = random.Next();
if(i+1 < list.Length)
{
list[i+1] = random.Next();
}
}
请务必了解您需要列表以获得索引器([x]数组表示法),因为某些集合没有,例如HashSet或Stack。
答案 4 :(得分:1)
有几种选择表明自己。
使集合(dm
)成为链表,而不是它是什么。
然后你可以写
while(obj.next != null)
{
var length = obj.Next.Start - obj.Start;
// whatever else you need to do in iteration
}
为每个对象添加一个属性,名为Collection
,其中包含对集合dm
的引用,以及另一个名为End
的属性。
public double? End // has to be nullable double to return null on last item
{
get
{
var nDx = Collection.IndexOf(this);
return Collection.Count > nDx+1? Collection[nDx + 1].Start: (double?)null;
}
}