2011-02-01 55 views
0

我有一个对象的数组,我需要迭代,修改和移位,我正在寻找一个最佳的解决方案this.Please你能帮我吗?如何将数组中的项目移动到紧邻的下一个索引?

假设我有一个包含50个对象的数组,最后两个索引包含无效对象,我打算做的是通过在指定索引处复制两个有效条目来删除它们。

var entries = profile.FindAll(entry=>entry.Date == DateTime.Now); 

for(int i=0;i<entries.Count;i++) 
{ 
if(i==2) 
//store the object at the 2nd position to the 4th index 
//However before storing this in the 4th index store the object in the 4th index to 5th index and the 5th index in the 6th..and so on 

if(i==3) 
//store the object at the 3rd position to the 5th index 
//However before storing this in the 5th index store the object in the 5th index to the 6th index and so on.. 

} 

//Basiacally once 'am out of this loop the items in the 2nd and 3rd index should be stored in the 4th and 5th index respectively, and the items in the 4th and 5th should be stored in the consecutive next index 
//Another complication to the story is that items in 2nd and 3rd indexes should be copied to 4th & 5th indexes at the same time, so that they are moved.Same should be the case of the consecutive indexes as well. 
//This way once I reach the end of the loop the items in the last two indexes of the array should be chucked out with duplicated values of 2nd and 3rd in 4th and 5th respectively and the array shifted. 

这是什么适当的数据结构,或者你会建议一个自定义算法?

感谢, -MT

+0

不知道为什么你要那样做,是什么主要目标是什么? – Magnus 2011-02-01 15:20:13

回答

0

尝试使用递归代替循环:

shift (list, index, index2) { 
    if (index < list.size()){ 
    shift(index+1, index2+2) 
    list[index2] = list[index] 
    } 
} 

在这种大方向:)

相关问题