在我的代码中,我有1000个索引的字符串数组,并且包含唯一的字符串数据。现在,我想复制其中一些字符串元素而不覆盖下一个元素。总而言之,我想移动数组并插入重复的值。
这是我的代码,
for (int r = 0; r < sResultarray1.Length; r++)
{
if (sResultarray1[r] != null &&
sResultarray1[r].Contains("WP") &&
sResultarray1[r].Contains("CB") == true)
{
index = Array.IndexOf(sResultarray1, sResultarray1[r]);
for (int e = 1000; e >= index + c; e--)
{
sResultarray1[e] = sResultarray1[e - c];
}
break;
}
}
我当前的输出是
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
我想要的输出是
++ST110+WP001.CB001
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
++ST130+WP001.CB001
有人帮助我解决这个问题吗?
答案 0 :(得分:1)
我建议使用不同集合类型-List<string>
代替String[]
(至少暂时):Add
,Insert
(“添加”)不是为操作数组设计的。像这样:
using System.Linq;
...
// Temporal collection - list
List<string> list = sResultarray1.ToList();
// Downward - we don't want to check the inserted item
for (int r = list.Count - 1; r >= 0; --r) {
if (list[r] != null && list[r].Contains("WP") && list[r].Contains("CB")) {
// if you want to insert - "shift and add duplicate value" - just insert
list.Insert(r + 1, list[r]);
}
}
// back to the array
sResultarray1 = list.ToArray();