【问题标题】:How do I move items in an array to the immediate next index?如何将数组中的项目移动到下一个索引?
【发布时间】:2011-02-01 12:14:38
【问题描述】:

我有一个需要迭代、修改和转移的对象数组,我正在为此寻找最佳解决方案。请您帮帮我吗?

假设我有一个包含 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

【问题讨论】:

  • 不知道为什么要这样做,主要目标是什么?

标签: c# arrays linq


【解决方案1】:

尝试使用递归而不是循环:

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

在那个大方向上:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 2021-12-15
    • 2016-11-15
    • 1970-01-01
    • 2017-09-30
    相关资源
    最近更新 更多