1

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?

4
  • When Adding, Inserting array (string[]) is not a good collection to work with. Try using List<string> Commented Dec 21, 2018 at 9:51
  • 1
    It would be better if your example outputs used strings that were more different, because right now it is more like the "find 5 errors" game. Commented Dec 21, 2018 at 10:03
  • Please, provide the initial array as well as actual an desired result. Commented Dec 21, 2018 at 10:04
  • Another option would be to have a collection of strings and counts, then duplicating becomes incrementing the counter and you don't have to change the collection. Commented Dec 21, 2018 at 11:38

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.