Piyush B
Piyush B

Reputation: 45

Shifting array and add duplicate of previous value

In my code I have string array of 1000 indexes and it contain unique string data. Now, I want to make duplicate of some of them string element without overwriting next element. To summarize I would like to shift the array and inserting a duplicate value.

Here my code is,

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;
     }
}

My current output is

++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001

My desired output is

++ST110+WP001.CB001
++ST110+WP001.CB001
++ST120+WP001.CB001
++ST120+WP001.CB001
++ST120+WP002.CB001
++ST120+WP002.CB001
++ST130+WP001.CB001
++ST130+WP001.CB001

Does anyone help me out to solve this problem?

Upvotes: 1

Views: 137

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

I suggest using different collection type - List<string> instead of String[] (at least temporarily): Add, Insert ("shift and add") are not operations array has been designed for. Something like this:

  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();

Upvotes: 1

Related Questions