2011-02-01 51 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] 
    } 
} 

在這種大方向:)

相關問題