Concatenate arrays accumulating content in C#

Asked

Viewed 701 times

2

Gentlemen, the question is the programming language C #, my question is: how can I place all the items of array B within each item of array A and the result will be stored in array C. Thank you.

Thank you in advance ...

public void TesteUniaoArray3()

{
    string[] one = new string[] { "XXXXX-X-XXX", "YYYYY-Y-YYY" };
    string[] two = new string[] { "1", "2", "3", "4", "5" };
    string[] three;

    three = new string[one.Length * two.Length];

    for (int i = 0; i <= one.Length; i++)
       for (int j = 0; j <= two.Length; j++)
            for (int idx = j; idx <= two.Length; idx++)
                try
                {
                    three[idx] = one[i] + "-" + two[j++];
                }

                catch (Exception)
                {
                    idx = three.Length;
                }
            }
        }
    }
}
  • 1

    To make it clear what you want to put the expected result.

  • Expected result in the array: XXXXX-X-XXX-1, XXXXX-X-XXX-2, XXXXX-X-XXX-3, XXXXX-X-XXX-4, XXXXX-X-XXX-5, YYYYY-Y-YYY-1, YYY-Y-YYY-2, YYYYY-Y-Y-Y-3, YYY-Y-Y-YYY-YYY-4, YYY-Y-Y-5

  • @Cleberpersonal, good life to Sopt. Please put the relevant comparison (as the desired result) as part of the question by editing it instead of commenting. This will give more visibility and make the community know quickly the point of the issue

1 answer

2


You used an extra loop, which ended up creating problem for you. It’s simpler to solve this way:

string[] one = new string[] { "XXXXX-X-XXX", "YYYYY-Y-YYY" };
string[] two = new string[] { "1", "2", "3", "4", "5" };
string[] three;

three = new string[one.Length * two.Length];

int idx = 0;

for (int i = 0; i < one.Length; i++)
    for (int j = 0; j < two.Length; j++)
    {
        three[idx] = one[i] + "-" + two[j];
        idx++;
    }

//foreach(var i in three)
//  Console.WriteLine(i);

The result would be according to what you expect, like can check in dotnetFiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.